1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-07-01 16:55:08 +02:00

use sync method on Responder trait (#1891)

This commit is contained in:
fakeshadow
2021-01-09 06:17:19 +08:00
committed by GitHub
parent 2204614134
commit d40ae8c8ca
10 changed files with 221 additions and 300 deletions

View File

@ -135,7 +135,6 @@ where
{
Extract(#[pin] T::Future, Option<HttpRequest>, F),
Handle(#[pin] R, Option<HttpRequest>),
Respond(#[pin] <R::Output as Responder>::Future, Option<HttpRequest>),
}
impl<F, T, R> Future for HandlerServiceFuture<F, T, R>
@ -168,13 +167,8 @@ where
}
HandlerProj::Handle(fut, req) => {
let res = ready!(fut.poll(cx));
let fut = res.respond_to(req.as_ref().unwrap());
let state = HandlerServiceFuture::Respond(fut, req.take());
self.as_mut().set(state);
}
HandlerProj::Respond(fut, req) => {
let res = ready!(fut.poll(cx)).unwrap_or_else(|e| e.into().into());
let req = req.take().unwrap();
let res = res.respond_to(&req);
return Poll::Ready(Ok(ServiceResponse::new(req, res)));
}
}

View File

@ -1,8 +1,4 @@
use std::convert::TryFrom;
use std::future::Future;
use std::marker::PhantomData;
use std::pin::Pin;
use std::task::{Context, Poll};
use actix_http::error::InternalError;
use actix_http::http::{
@ -10,9 +6,6 @@ use actix_http::http::{
};
use actix_http::{Error, Response, ResponseBuilder};
use bytes::{Bytes, BytesMut};
use futures_util::future::{err, ok, Either as EitherFuture, Ready};
use futures_util::ready;
use pin_project::pin_project;
use crate::request::HttpRequest;
@ -20,14 +13,8 @@ use crate::request::HttpRequest;
///
/// Types that implement this trait can be used as the return type of a handler.
pub trait Responder {
/// The associated error which can be returned.
type Error: Into<Error>;
/// The future response value.
type Future: Future<Output = Result<Response, Self::Error>>;
/// Convert itself to `AsyncResult` or `Error`.
fn respond_to(self, req: &HttpRequest) -> Self::Future;
/// Convert self to `Response`.
fn respond_to(self, req: &HttpRequest) -> Response;
/// Override a status code for a Responder.
///
@ -77,28 +64,17 @@ pub trait Responder {
}
impl Responder for Response {
type Error = Error;
type Future = Ready<Result<Response, Error>>;
#[inline]
fn respond_to(self, _: &HttpRequest) -> Self::Future {
ok(self)
fn respond_to(self, _: &HttpRequest) -> Response {
self
}
}
impl<T> Responder for Option<T>
where
T: Responder,
{
type Error = T::Error;
type Future = EitherFuture<T::Future, Ready<Result<Response, T::Error>>>;
fn respond_to(self, req: &HttpRequest) -> Self::Future {
impl<T: Responder> Responder for Option<T> {
fn respond_to(self, req: &HttpRequest) -> Response {
match self {
Some(t) => EitherFuture::Left(t.respond_to(req)),
None => {
EitherFuture::Right(ok(Response::build(StatusCode::NOT_FOUND).finish()))
}
Some(t) => t.respond_to(req),
None => Response::build(StatusCode::NOT_FOUND).finish(),
}
}
}
@ -108,109 +84,74 @@ where
T: Responder,
E: Into<Error>,
{
type Error = Error;
type Future = EitherFuture<
ResponseFuture<T::Future, T::Error>,
Ready<Result<Response, Error>>,
>;
fn respond_to(self, req: &HttpRequest) -> Self::Future {
fn respond_to(self, req: &HttpRequest) -> Response {
match self {
Ok(val) => EitherFuture::Left(ResponseFuture::new(val.respond_to(req))),
Err(e) => EitherFuture::Right(err(e.into())),
Ok(val) => val.respond_to(req),
Err(e) => Response::from_error(e.into()),
}
}
}
impl Responder for ResponseBuilder {
type Error = Error;
type Future = Ready<Result<Response, Error>>;
#[inline]
fn respond_to(mut self, _: &HttpRequest) -> Self::Future {
ok(self.finish())
fn respond_to(mut self, _: &HttpRequest) -> Response {
self.finish()
}
}
impl<T> Responder for (T, StatusCode)
where
T: Responder,
{
type Error = T::Error;
type Future = CustomResponderFut<T>;
fn respond_to(self, req: &HttpRequest) -> Self::Future {
CustomResponderFut {
fut: self.0.respond_to(req),
status: Some(self.1),
headers: None,
}
impl<T: Responder> Responder for (T, StatusCode) {
fn respond_to(self, req: &HttpRequest) -> Response {
let mut res = self.0.respond_to(req);
*res.status_mut() = self.1;
res
}
}
impl Responder for &'static str {
type Error = Error;
type Future = Ready<Result<Response, Error>>;
fn respond_to(self, _: &HttpRequest) -> Self::Future {
ok(Response::build(StatusCode::OK)
fn respond_to(self, _: &HttpRequest) -> Response {
Response::build(StatusCode::OK)
.content_type("text/plain; charset=utf-8")
.body(self))
.body(self)
}
}
impl Responder for &'static [u8] {
type Error = Error;
type Future = Ready<Result<Response, Error>>;
fn respond_to(self, _: &HttpRequest) -> Self::Future {
ok(Response::build(StatusCode::OK)
fn respond_to(self, _: &HttpRequest) -> Response {
Response::build(StatusCode::OK)
.content_type("application/octet-stream")
.body(self))
.body(self)
}
}
impl Responder for String {
type Error = Error;
type Future = Ready<Result<Response, Error>>;
fn respond_to(self, _: &HttpRequest) -> Self::Future {
ok(Response::build(StatusCode::OK)
fn respond_to(self, _: &HttpRequest) -> Response {
Response::build(StatusCode::OK)
.content_type("text/plain; charset=utf-8")
.body(self))
.body(self)
}
}
impl<'a> Responder for &'a String {
type Error = Error;
type Future = Ready<Result<Response, Error>>;
fn respond_to(self, _: &HttpRequest) -> Self::Future {
ok(Response::build(StatusCode::OK)
fn respond_to(self, _: &HttpRequest) -> Response {
Response::build(StatusCode::OK)
.content_type("text/plain; charset=utf-8")
.body(self))
.body(self)
}
}
impl Responder for Bytes {
type Error = Error;
type Future = Ready<Result<Response, Error>>;
fn respond_to(self, _: &HttpRequest) -> Self::Future {
ok(Response::build(StatusCode::OK)
fn respond_to(self, _: &HttpRequest) -> Response {
Response::build(StatusCode::OK)
.content_type("application/octet-stream")
.body(self))
.body(self)
}
}
impl Responder for BytesMut {
type Error = Error;
type Future = Ready<Result<Response, Error>>;
fn respond_to(self, _: &HttpRequest) -> Self::Future {
ok(Response::build(StatusCode::OK)
fn respond_to(self, _: &HttpRequest) -> Response {
Response::build(StatusCode::OK)
.content_type("application/octet-stream")
.body(self))
.body(self)
}
}
@ -290,45 +231,20 @@ impl<T: Responder> CustomResponder<T> {
}
impl<T: Responder> Responder for CustomResponder<T> {
type Error = T::Error;
type Future = CustomResponderFut<T>;
fn respond_to(self, req: &HttpRequest) -> Response {
let mut res = self.responder.respond_to(req);
fn respond_to(self, req: &HttpRequest) -> Self::Future {
CustomResponderFut {
fut: self.responder.respond_to(req),
status: self.status,
headers: self.headers,
}
}
}
#[pin_project]
pub struct CustomResponderFut<T: Responder> {
#[pin]
fut: T::Future,
status: Option<StatusCode>,
headers: Option<HeaderMap>,
}
impl<T: Responder> Future for CustomResponderFut<T> {
type Output = Result<Response, T::Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
let mut res = match ready!(this.fut.poll(cx)) {
Ok(res) => res,
Err(e) => return Poll::Ready(Err(e)),
};
if let Some(status) = this.status.take() {
if let Some(status) = self.status {
*res.status_mut() = status;
}
if let Some(ref headers) = this.headers {
if let Some(ref headers) = self.headers {
for (k, v) in headers {
res.headers_mut().insert(k.clone(), v.clone());
}
}
Poll::Ready(Ok(res))
res
}
}
@ -336,40 +252,8 @@ impl<T> Responder for InternalError<T>
where
T: std::fmt::Debug + std::fmt::Display + 'static,
{
type Error = Error;
type Future = Ready<Result<Response, Error>>;
fn respond_to(self, _: &HttpRequest) -> Self::Future {
let err: Error = self.into();
ok(err.into())
}
}
#[pin_project]
pub struct ResponseFuture<T, E> {
#[pin]
fut: T,
_phantom: PhantomData<E>,
}
impl<T, E> ResponseFuture<T, E> {
pub fn new(fut: T) -> Self {
ResponseFuture {
fut,
_phantom: PhantomData,
}
}
}
impl<T, E> Future for ResponseFuture<T, E>
where
T: Future<Output = Result<Response, E>>,
E: Into<Error>,
{
type Output = Result<Response, Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Poll::Ready(ready!(self.project().fut.poll(cx)).map_err(|e| e.into()))
fn respond_to(self, _: &HttpRequest) -> Response {
Response::from_error(self.into())
}
}
@ -382,7 +266,7 @@ pub(crate) mod tests {
use crate::dev::{Body, ResponseBody};
use crate::http::{header::CONTENT_TYPE, HeaderValue, StatusCode};
use crate::test::{init_service, TestRequest};
use crate::{error, web, App, HttpResponse};
use crate::{error, web, App};
#[actix_rt::test]
async fn test_option_responder() {
@ -441,7 +325,7 @@ pub(crate) mod tests {
async fn test_responder() {
let req = TestRequest::default().to_http_request();
let resp: HttpResponse = "test".respond_to(&req).await.unwrap();
let resp = "test".respond_to(&req);
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().bin_ref(), b"test");
assert_eq!(
@ -449,7 +333,7 @@ pub(crate) mod tests {
HeaderValue::from_static("text/plain; charset=utf-8")
);
let resp: HttpResponse = b"test".respond_to(&req).await.unwrap();
let resp = b"test".respond_to(&req);
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().bin_ref(), b"test");
assert_eq!(
@ -457,7 +341,7 @@ pub(crate) mod tests {
HeaderValue::from_static("application/octet-stream")
);
let resp: HttpResponse = "test".to_string().respond_to(&req).await.unwrap();
let resp = "test".to_string().respond_to(&req);
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().bin_ref(), b"test");
assert_eq!(
@ -465,7 +349,7 @@ pub(crate) mod tests {
HeaderValue::from_static("text/plain; charset=utf-8")
);
let resp: HttpResponse = (&"test".to_string()).respond_to(&req).await.unwrap();
let resp = (&"test".to_string()).respond_to(&req);
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().bin_ref(), b"test");
assert_eq!(
@ -473,8 +357,7 @@ pub(crate) mod tests {
HeaderValue::from_static("text/plain; charset=utf-8")
);
let resp: HttpResponse =
Bytes::from_static(b"test").respond_to(&req).await.unwrap();
let resp = Bytes::from_static(b"test").respond_to(&req);
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().bin_ref(), b"test");
assert_eq!(
@ -482,10 +365,7 @@ pub(crate) mod tests {
HeaderValue::from_static("application/octet-stream")
);
let resp: HttpResponse = BytesMut::from(b"test".as_ref())
.respond_to(&req)
.await
.unwrap();
let resp = BytesMut::from(b"test".as_ref()).respond_to(&req);
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().bin_ref(), b"test");
assert_eq!(
@ -494,11 +374,8 @@ pub(crate) mod tests {
);
// InternalError
let resp: HttpResponse =
error::InternalError::new("err", StatusCode::BAD_REQUEST)
.respond_to(&req)
.await
.unwrap();
let resp =
error::InternalError::new("err", StatusCode::BAD_REQUEST).respond_to(&req);
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
}
@ -507,10 +384,7 @@ pub(crate) mod tests {
let req = TestRequest::default().to_http_request();
// Result<I, E>
let resp: HttpResponse = Ok::<_, Error>("test".to_string())
.respond_to(&req)
.await
.unwrap();
let resp = Ok::<_, Error>("test".to_string()).respond_to(&req);
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.body().bin_ref(), b"test");
assert_eq!(
@ -520,9 +394,9 @@ pub(crate) mod tests {
let res =
Err::<String, _>(error::InternalError::new("err", StatusCode::BAD_REQUEST))
.respond_to(&req)
.await;
assert!(res.is_err());
.respond_to(&req);
assert_eq!(res.status(), StatusCode::BAD_REQUEST);
}
#[actix_rt::test]
@ -531,18 +405,15 @@ pub(crate) mod tests {
let res = "test"
.to_string()
.with_status(StatusCode::BAD_REQUEST)
.respond_to(&req)
.await
.unwrap();
.respond_to(&req);
assert_eq!(res.status(), StatusCode::BAD_REQUEST);
assert_eq!(res.body().bin_ref(), b"test");
let res = "test"
.to_string()
.with_header("content-type", "json")
.respond_to(&req)
.await
.unwrap();
.respond_to(&req);
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.body().bin_ref(), b"test");
@ -555,19 +426,14 @@ pub(crate) mod tests {
#[actix_rt::test]
async fn test_tuple_responder_with_status_code() {
let req = TestRequest::default().to_http_request();
let res = ("test".to_string(), StatusCode::BAD_REQUEST)
.respond_to(&req)
.await
.unwrap();
let res = ("test".to_string(), StatusCode::BAD_REQUEST).respond_to(&req);
assert_eq!(res.status(), StatusCode::BAD_REQUEST);
assert_eq!(res.body().bin_ref(), b"test");
let req = TestRequest::default().to_http_request();
let res = ("test".to_string(), StatusCode::OK)
.with_header("content-type", "json")
.respond_to(&req)
.await
.unwrap();
.respond_to(&req);
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.body().bin_ref(), b"test");
assert_eq!(

View File

@ -1,13 +1,6 @@
use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
};
use actix_http::{Error, Response};
use bytes::Bytes;
use futures_util::{future::LocalBoxFuture, ready, FutureExt, TryFutureExt};
use pin_project::pin_project;
use futures_util::{future::LocalBoxFuture, FutureExt, TryFutureExt};
use crate::{dev, request::HttpRequest, FromRequest, Responder};
@ -68,42 +61,10 @@ where
A: Responder,
B: Responder,
{
type Error = Error;
type Future = EitherResponder<A, B>;
fn respond_to(self, req: &HttpRequest) -> Self::Future {
fn respond_to(self, req: &HttpRequest) -> Response {
match self {
Either::A(a) => EitherResponder::A(a.respond_to(req)),
Either::B(b) => EitherResponder::B(b.respond_to(req)),
}
}
}
#[pin_project(project = EitherResponderProj)]
pub enum EitherResponder<A, B>
where
A: Responder,
B: Responder,
{
A(#[pin] A::Future),
B(#[pin] B::Future),
}
impl<A, B> Future for EitherResponder<A, B>
where
A: Responder,
B: Responder,
{
type Output = Result<Response, Error>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
match self.project() {
EitherResponderProj::A(fut) => {
Poll::Ready(ready!(fut.poll(cx)).map_err(|e| e.into()))
}
EitherResponderProj::B(fut) => {
Poll::Ready(ready!(fut.poll(cx).map_err(|e| e.into())))
}
Either::A(a) => a.respond_to(req),
Either::B(b) => b.respond_to(req),
}
}
}

View File

@ -9,7 +9,7 @@ use std::{fmt, ops};
use actix_http::{Error, HttpMessage, Payload, Response};
use bytes::BytesMut;
use encoding_rs::{Encoding, UTF_8};
use futures_util::future::{err, ok, FutureExt, LocalBoxFuture, Ready};
use futures_util::future::{FutureExt, LocalBoxFuture};
use futures_util::StreamExt;
use serde::de::DeserializeOwned;
use serde::Serialize;
@ -158,18 +158,13 @@ impl<T: fmt::Display> fmt::Display for Form<T> {
}
impl<T: Serialize> Responder for Form<T> {
type Error = Error;
type Future = Ready<Result<Response, Error>>;
fn respond_to(self, _: &HttpRequest) -> Self::Future {
let body = match serde_urlencoded::to_string(&self.0) {
Ok(body) => body,
Err(e) => return err(e.into()),
};
ok(Response::build(StatusCode::OK)
.set(ContentType::form_url_encoded())
.body(body))
fn respond_to(self, _: &HttpRequest) -> Response {
match serde_urlencoded::to_string(&self.0) {
Ok(body) => Response::build(StatusCode::OK)
.set(ContentType::form_url_encoded())
.body(body),
Err(e) => Response::from_error(e.into()),
}
}
}
@ -493,7 +488,7 @@ mod tests {
hello: "world".to_string(),
counter: 123,
});
let resp = form.respond_to(&req).await.unwrap();
let resp = form.respond_to(&req);
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.headers().get(CONTENT_TYPE).unwrap(),

View File

@ -8,7 +8,6 @@ use std::task::{Context, Poll};
use std::{fmt, ops};
use bytes::BytesMut;
use futures_util::future::{ready, Ready};
use futures_util::ready;
use futures_util::stream::Stream;
use serde::de::DeserializeOwned;
@ -123,18 +122,13 @@ where
}
impl<T: Serialize> Responder for Json<T> {
type Error = Error;
type Future = Ready<Result<Response, Error>>;
fn respond_to(self, _: &HttpRequest) -> Self::Future {
let body = match serde_json::to_string(&self.0) {
Ok(body) => body,
Err(e) => return ready(Err(e.into())),
};
ready(Ok(Response::build(StatusCode::OK)
.content_type("application/json")
.body(body)))
fn respond_to(self, _: &HttpRequest) -> Response {
match serde_json::to_string(&self.0) {
Ok(body) => Response::build(StatusCode::OK)
.content_type("application/json")
.body(body),
Err(e) => Response::from_error(e.into()),
}
}
}
@ -498,7 +492,7 @@ mod tests {
let j = Json(MyObject {
name: "test".to_string(),
});
let resp = j.respond_to(&req).await.unwrap();
let resp = j.respond_to(&req);
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.headers().get(header::CONTENT_TYPE).unwrap(),