1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-30 18:44:35 +01: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
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 221 additions and 300 deletions

View File

@ -1,7 +1,11 @@
# Changes # Changes
## Unreleased - 2021-xx-xx ## Unreleased - 2021-xx-xx
### Changed
* Rework `Responder` trait to be sync and returns `Response`/`HttpResponse` directly.
Making it more simple and performant. [#1891]
[#1891]: https://github.com/actix/actix-web/pull/1891
## 4.0.0-beta.1 - 2021-01-07 ## 4.0.0-beta.1 - 2021-01-07
### Added ### Added

View File

@ -139,3 +139,7 @@ harness = false
[[bench]] [[bench]]
name = "service" name = "service"
harness = false harness = false
[[bench]]
name = "responder"
harness = false

View File

@ -16,10 +16,9 @@ use actix_web::{
}, },
ContentEncoding, StatusCode, ContentEncoding, StatusCode,
}, },
Error, HttpMessage, HttpRequest, HttpResponse, Responder, HttpMessage, HttpRequest, HttpResponse, Responder,
}; };
use bitflags::bitflags; use bitflags::bitflags;
use futures_util::future::{ready, Ready};
use mime_guess::from_path; use mime_guess::from_path;
use crate::ChunkedReadFile; use crate::ChunkedReadFile;
@ -277,7 +276,7 @@ impl NamedFile {
} }
/// Creates an `HttpResponse` with file as a streaming body. /// Creates an `HttpResponse` with file as a streaming body.
pub fn into_response(self, req: &HttpRequest) -> Result<HttpResponse, Error> { pub fn into_response(self, req: &HttpRequest) -> HttpResponse {
if self.status_code != StatusCode::OK { if self.status_code != StatusCode::OK {
let mut res = HttpResponse::build(self.status_code); let mut res = HttpResponse::build(self.status_code);
@ -307,7 +306,7 @@ impl NamedFile {
counter: 0, counter: 0,
}; };
return Ok(res.streaming(reader)); return res.streaming(reader);
} }
let etag = if self.flags.contains(Flags::ETAG) { let etag = if self.flags.contains(Flags::ETAG) {
@ -411,17 +410,17 @@ impl NamedFile {
); );
} else { } else {
resp.header(header::CONTENT_RANGE, format!("bytes */{}", length)); resp.header(header::CONTENT_RANGE, format!("bytes */{}", length));
return Ok(resp.status(StatusCode::RANGE_NOT_SATISFIABLE).finish()); return resp.status(StatusCode::RANGE_NOT_SATISFIABLE).finish();
}; };
} else { } else {
return Ok(resp.status(StatusCode::BAD_REQUEST).finish()); return resp.status(StatusCode::BAD_REQUEST).finish();
}; };
}; };
if precondition_failed { if precondition_failed {
return Ok(resp.status(StatusCode::PRECONDITION_FAILED).finish()); return resp.status(StatusCode::PRECONDITION_FAILED).finish();
} else if not_modified { } else if not_modified {
return Ok(resp.status(StatusCode::NOT_MODIFIED).finish()); return resp.status(StatusCode::NOT_MODIFIED).finish();
} }
let reader = ChunkedReadFile { let reader = ChunkedReadFile {
@ -436,7 +435,7 @@ impl NamedFile {
resp.status(StatusCode::PARTIAL_CONTENT); resp.status(StatusCode::PARTIAL_CONTENT);
} }
Ok(resp.body(SizedStream::new(length, reader))) resp.body(SizedStream::new(length, reader))
} }
} }
@ -495,10 +494,7 @@ fn none_match(etag: Option<&header::EntityTag>, req: &HttpRequest) -> bool {
} }
impl Responder for NamedFile { impl Responder for NamedFile {
type Error = Error; fn respond_to(self, req: &HttpRequest) -> HttpResponse {
type Future = Ready<Result<HttpResponse, Error>>; self.into_response(req)
fn respond_to(self, req: &HttpRequest) -> Self::Future {
ready(self.into_response(req))
} }
} }

View File

@ -120,10 +120,8 @@ impl Service<ServiceRequest> for FilesService {
named_file.flags = self.file_flags; named_file.flags = self.file_flags;
let (req, _) = req.into_parts(); let (req, _) = req.into_parts();
Either::Left(ok(match named_file.into_response(&req) { let res = named_file.into_response(&req);
Ok(item) => ServiceResponse::new(req, item), Either::Left(ok(ServiceResponse::new(req, res)))
Err(e) => ServiceResponse::from_err(e, req),
}))
} }
Err(e) => self.handle_err(e, req), Err(e) => self.handle_err(e, req),
} }
@ -154,12 +152,8 @@ impl Service<ServiceRequest> for FilesService {
named_file.flags = self.file_flags; named_file.flags = self.file_flags;
let (req, _) = req.into_parts(); let (req, _) = req.into_parts();
match named_file.into_response(&req) { let res = named_file.into_response(&req);
Ok(item) => { Either::Left(ok(ServiceResponse::new(req, res)))
Either::Left(ok(ServiceResponse::new(req.clone(), item)))
}
Err(e) => Either::Left(ok(ServiceResponse::from_err(e, req))),
}
} }
Err(e) => self.handle_err(e, req), Err(e) => self.handle_err(e, req),
} }

113
benches/responder.rs Normal file
View File

@ -0,0 +1,113 @@
use std::future::Future;
use std::time::Instant;
use actix_http::Response;
use actix_web::http::StatusCode;
use actix_web::test::TestRequest;
use actix_web::{error, Error, HttpRequest, HttpResponse, Responder};
use criterion::{criterion_group, criterion_main, Criterion};
use futures_util::future::{ready, Either, Ready};
// responder simulate the old responder trait.
trait FutureResponder {
type Error;
type Future: Future<Output = Result<HttpResponse, Self::Error>>;
fn future_respond_to(self, req: &HttpRequest) -> Self::Future;
}
// a simple option responder type.
struct OptionResponder<T>(Option<T>);
// a simple wrapper type around string
struct StringResponder(String);
impl FutureResponder for StringResponder {
type Error = Error;
type Future = Ready<Result<Response, Self::Error>>;
fn future_respond_to(self, _: &HttpRequest) -> Self::Future {
// this is default builder for string response in both new and old responder trait.
ready(Ok(Response::build(StatusCode::OK)
.content_type("text/plain; charset=utf-8")
.body(self.0)))
}
}
impl<T> FutureResponder for OptionResponder<T>
where
T: FutureResponder,
T::Future: Future<Output = Result<Response, Error>>,
{
type Error = Error;
type Future = Either<T::Future, Ready<Result<HttpResponse, Self::Error>>>;
fn future_respond_to(self, req: &HttpRequest) -> Self::Future {
match self.0 {
Some(t) => Either::Left(t.future_respond_to(req)),
None => Either::Right(ready(Err(error::ErrorInternalServerError("err")))),
}
}
}
impl Responder for StringResponder {
fn respond_to(self, _: &HttpRequest) -> HttpResponse {
Response::build(StatusCode::OK)
.content_type("text/plain; charset=utf-8")
.body(self.0)
}
}
impl<T: Responder> Responder for OptionResponder<T> {
fn respond_to(self, req: &HttpRequest) -> HttpResponse {
match self.0 {
Some(t) => t.respond_to(req),
None => Response::from_error(error::ErrorInternalServerError("err")),
}
}
}
fn future_responder(c: &mut Criterion) {
let rt = actix_rt::System::new("test");
let req = TestRequest::default().to_http_request();
c.bench_function("future_responder", move |b| {
b.iter_custom(|_| {
let futs = (0..100_000).map(|_| async {
StringResponder(String::from("Hello World!!"))
.future_respond_to(&req)
.await
});
let futs = futures_util::future::join_all(futs);
let start = Instant::now();
let _res = rt.block_on(async { futs.await });
start.elapsed()
})
});
}
fn responder(c: &mut Criterion) {
let rt = actix_rt::System::new("test");
let req = TestRequest::default().to_http_request();
c.bench_function("responder", move |b| {
b.iter_custom(|_| {
let responders =
(0..100_000).map(|_| StringResponder(String::from("Hello World!!")));
let start = Instant::now();
let _res = rt.block_on(async {
// don't need runtime block on but to be fair.
responders.map(|r| r.respond_to(&req)).collect::<Vec<_>>()
});
start.elapsed()
})
});
}
criterion_group!(responder_bench, future_responder, responder);
criterion_main!(responder_bench);

View File

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

View File

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

View File

@ -1,13 +1,6 @@
use std::{
future::Future,
pin::Pin,
task::{Context, Poll},
};
use actix_http::{Error, Response}; use actix_http::{Error, Response};
use bytes::Bytes; use bytes::Bytes;
use futures_util::{future::LocalBoxFuture, ready, FutureExt, TryFutureExt}; use futures_util::{future::LocalBoxFuture, FutureExt, TryFutureExt};
use pin_project::pin_project;
use crate::{dev, request::HttpRequest, FromRequest, Responder}; use crate::{dev, request::HttpRequest, FromRequest, Responder};
@ -68,42 +61,10 @@ where
A: Responder, A: Responder,
B: Responder, B: Responder,
{ {
type Error = Error; fn respond_to(self, req: &HttpRequest) -> Response {
type Future = EitherResponder<A, B>;
fn respond_to(self, req: &HttpRequest) -> Self::Future {
match self { match self {
Either::A(a) => EitherResponder::A(a.respond_to(req)), Either::A(a) => a.respond_to(req),
Either::B(b) => EitherResponder::B(b.respond_to(req)), Either::B(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())))
}
} }
} }
} }

View File

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

View File

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