1
0
mirror of https://github.com/fafhrd91/actix-web synced 2025-07-24 09:47:49 +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

@@ -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!(