mirror of
https://github.com/fafhrd91/actix-web
synced 2025-07-01 16:55:08 +02:00
remove responsebody indirection from response (#2201)
This commit is contained in:
@ -166,8 +166,7 @@ impl AppInitServiceState {
|
||||
Rc::new(AppInitServiceState {
|
||||
rmap,
|
||||
config,
|
||||
// TODO: AppConfig can be used to pass user defined HttpRequestPool
|
||||
// capacity.
|
||||
// TODO: AppConfig can be used to pass user defined HttpRequestPool capacity.
|
||||
pool: HttpRequestPool::default(),
|
||||
})
|
||||
}
|
||||
|
@ -9,6 +9,11 @@ use url::ParseError as UrlParseError;
|
||||
|
||||
use crate::http::StatusCode;
|
||||
|
||||
/// A convenience [`Result`](std::result::Result) for Actix Web operations.
|
||||
///
|
||||
/// This type alias is generally used to avoid writing out `actix_http::Error` directly.
|
||||
pub type Result<T, E = actix_http::Error> = std::result::Result<T, E>;
|
||||
|
||||
/// Errors which can occur when attempting to generate resource uri.
|
||||
#[derive(Debug, PartialEq, Display, Error, From)]
|
||||
#[non_exhaustive]
|
||||
@ -26,7 +31,6 @@ pub enum UrlGenerationError {
|
||||
ParseError(UrlParseError),
|
||||
}
|
||||
|
||||
/// `InternalServerError` for `UrlGeneratorError`
|
||||
impl ResponseError for UrlGenerationError {}
|
||||
|
||||
/// A set of errors that can occur during parsing urlencoded payloads
|
||||
@ -70,7 +74,6 @@ pub enum UrlencodedError {
|
||||
Payload(PayloadError),
|
||||
}
|
||||
|
||||
/// Return `BadRequest` for `UrlencodedError`
|
||||
impl ResponseError for UrlencodedError {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
match self {
|
||||
@ -149,7 +152,6 @@ pub enum QueryPayloadError {
|
||||
Deserialize(serde::de::value::Error),
|
||||
}
|
||||
|
||||
/// Return `BadRequest` for `QueryPayloadError`
|
||||
impl ResponseError for QueryPayloadError {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
StatusCode::BAD_REQUEST
|
||||
@ -177,7 +179,6 @@ pub enum ReadlinesError {
|
||||
ContentTypeError(ContentTypeError),
|
||||
}
|
||||
|
||||
/// Return `BadRequest` for `ReadlinesError`
|
||||
impl ResponseError for ReadlinesError {
|
||||
fn status_code(&self) -> StatusCode {
|
||||
match *self {
|
||||
|
@ -97,7 +97,7 @@ pub(crate) mod types;
|
||||
pub mod web;
|
||||
|
||||
pub use actix_http::Response as BaseHttpResponse;
|
||||
pub use actix_http::{body, Error, HttpMessage, ResponseError, Result};
|
||||
pub use actix_http::{body, Error, HttpMessage, ResponseError};
|
||||
#[doc(inline)]
|
||||
pub use actix_rt as rt;
|
||||
pub use actix_web_codegen::*;
|
||||
@ -105,6 +105,7 @@ pub use actix_web_codegen::*;
|
||||
pub use cookie;
|
||||
|
||||
pub use crate::app::App;
|
||||
pub use crate::error::Result;
|
||||
pub use crate::extract::FromRequest;
|
||||
pub use crate::request::HttpRequest;
|
||||
pub use crate::resource::Resource;
|
||||
|
@ -1,12 +1,13 @@
|
||||
//! For middleware documentation, see [`Compat`].
|
||||
|
||||
use std::{
|
||||
error::Error as StdError,
|
||||
future::Future,
|
||||
pin::Pin,
|
||||
task::{Context, Poll},
|
||||
};
|
||||
|
||||
use actix_http::body::{Body, MessageBody, ResponseBody};
|
||||
use actix_http::body::{Body, MessageBody};
|
||||
use actix_service::{Service, Transform};
|
||||
use futures_core::{future::LocalBoxFuture, ready};
|
||||
|
||||
@ -116,10 +117,10 @@ pub trait MapServiceResponseBody {
|
||||
impl<B> MapServiceResponseBody for ServiceResponse<B>
|
||||
where
|
||||
B: MessageBody + Unpin + 'static,
|
||||
B::Error: Into<Error>,
|
||||
B::Error: Into<Box<dyn StdError + 'static>>,
|
||||
{
|
||||
fn map_body(self) -> ServiceResponse {
|
||||
self.map_body(|_, body| ResponseBody::Other(Body::from_message(body)))
|
||||
self.map_body(|_, body| Body::from_message(body))
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -10,7 +10,7 @@ use std::{
|
||||
};
|
||||
|
||||
use actix_http::{
|
||||
body::MessageBody,
|
||||
body::{MessageBody, ResponseBody},
|
||||
encoding::Encoder,
|
||||
http::header::{ContentEncoding, ACCEPT_ENCODING},
|
||||
Error,
|
||||
@ -59,7 +59,7 @@ where
|
||||
B: MessageBody,
|
||||
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||
{
|
||||
type Response = ServiceResponse<Encoder<B>>;
|
||||
type Response = ServiceResponse<ResponseBody<Encoder<B>>>;
|
||||
type Error = Error;
|
||||
type Transform = CompressMiddleware<S>;
|
||||
type InitError = ();
|
||||
@ -83,7 +83,7 @@ where
|
||||
B: MessageBody,
|
||||
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||
{
|
||||
type Response = ServiceResponse<Encoder<B>>;
|
||||
type Response = ServiceResponse<ResponseBody<Encoder<B>>>;
|
||||
type Error = Error;
|
||||
type Future = CompressResponse<S, B>;
|
||||
|
||||
@ -127,7 +127,7 @@ where
|
||||
B: MessageBody,
|
||||
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
|
||||
{
|
||||
type Output = Result<ServiceResponse<Encoder<B>>, Error>;
|
||||
type Output = Result<ServiceResponse<ResponseBody<Encoder<B>>>, Error>;
|
||||
|
||||
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
let this = self.project();
|
||||
@ -140,9 +140,9 @@ where
|
||||
*this.encoding
|
||||
};
|
||||
|
||||
Poll::Ready(Ok(
|
||||
resp.map_body(move |head, body| Encoder::response(enc, head, body))
|
||||
))
|
||||
Poll::Ready(Ok(resp.map_body(move |head, body| {
|
||||
Encoder::response(enc, head, ResponseBody::Body(body))
|
||||
})))
|
||||
}
|
||||
Err(e) => Poll::Ready(Err(e)),
|
||||
}
|
||||
|
@ -21,7 +21,7 @@ use regex::{Regex, RegexSet};
|
||||
use time::OffsetDateTime;
|
||||
|
||||
use crate::{
|
||||
dev::{BodySize, MessageBody, ResponseBody},
|
||||
dev::{BodySize, MessageBody},
|
||||
http::{HeaderName, StatusCode},
|
||||
service::{ServiceRequest, ServiceResponse},
|
||||
Error, HttpResponse, Result,
|
||||
@ -289,13 +289,11 @@ where
|
||||
let time = *this.time;
|
||||
let format = this.format.take();
|
||||
|
||||
Poll::Ready(Ok(res.map_body(move |_, body| {
|
||||
ResponseBody::Body(StreamLog {
|
||||
body,
|
||||
time,
|
||||
format,
|
||||
size: 0,
|
||||
})
|
||||
Poll::Ready(Ok(res.map_body(move |_, body| StreamLog {
|
||||
body,
|
||||
time,
|
||||
format,
|
||||
size: 0,
|
||||
})))
|
||||
}
|
||||
}
|
||||
@ -305,7 +303,7 @@ use pin_project::{pin_project, pinned_drop};
|
||||
#[pin_project(PinnedDrop)]
|
||||
pub struct StreamLog<B> {
|
||||
#[pin]
|
||||
body: ResponseBody<B>,
|
||||
body: B,
|
||||
format: Option<Format>,
|
||||
size: usize,
|
||||
time: OffsetDateTime,
|
||||
@ -342,12 +340,15 @@ where
|
||||
cx: &mut Context<'_>,
|
||||
) -> Poll<Option<Result<Bytes, Self::Error>>> {
|
||||
let this = self.project();
|
||||
match this.body.poll_next(cx) {
|
||||
Poll::Ready(Some(Ok(chunk))) => {
|
||||
|
||||
// TODO: MSRV 1.51: poll_map_err
|
||||
match ready!(this.body.poll_next(cx)) {
|
||||
Some(Ok(chunk)) => {
|
||||
*this.size += chunk.len();
|
||||
Poll::Ready(Some(Ok(chunk)))
|
||||
}
|
||||
val => val,
|
||||
Some(Err(err)) => Poll::Ready(Some(Err(err.into()))),
|
||||
None => Poll::Ready(None),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -264,7 +264,7 @@ pub(crate) mod tests {
|
||||
let resp = srv.call(req).await.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
match resp.response().body() {
|
||||
ResponseBody::Body(Body::Bytes(ref b)) => {
|
||||
Body::Bytes(ref b) => {
|
||||
let bytes = b.clone();
|
||||
assert_eq!(bytes, Bytes::from_static(b"some"));
|
||||
}
|
||||
@ -277,16 +277,28 @@ pub(crate) mod tests {
|
||||
fn body(&self) -> &Body;
|
||||
}
|
||||
|
||||
impl BodyTest for Body {
|
||||
fn bin_ref(&self) -> &[u8] {
|
||||
match self {
|
||||
Body::Bytes(ref bin) => &bin,
|
||||
_ => unreachable!("bug in test impl"),
|
||||
}
|
||||
}
|
||||
fn body(&self) -> &Body {
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl BodyTest for ResponseBody<Body> {
|
||||
fn bin_ref(&self) -> &[u8] {
|
||||
match self {
|
||||
ResponseBody::Body(ref b) => match b {
|
||||
Body::Bytes(ref bin) => &bin,
|
||||
_ => panic!(),
|
||||
_ => unreachable!("bug in test impl"),
|
||||
},
|
||||
ResponseBody::Other(ref b) => match b {
|
||||
Body::Bytes(ref bin) => &bin,
|
||||
_ => panic!(),
|
||||
_ => unreachable!("bug in test impl"),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
@ -310,16 +310,19 @@ impl HttpResponseBuilder {
|
||||
///
|
||||
/// `HttpResponseBuilder` can not be used after this call.
|
||||
#[inline]
|
||||
pub fn body<B: Into<Body>>(&mut self, body: B) -> HttpResponse {
|
||||
self.message_body(body.into())
|
||||
pub fn body<B: Into<Body>>(&mut self, body: B) -> HttpResponse<Body> {
|
||||
match self.message_body(body.into()) {
|
||||
Ok(res) => res,
|
||||
Err(err) => HttpResponse::from_error(err),
|
||||
}
|
||||
}
|
||||
|
||||
/// Set a body and generate `Response`.
|
||||
///
|
||||
/// `HttpResponseBuilder` can not be used after this call.
|
||||
pub fn message_body<B>(&mut self, body: B) -> HttpResponse<B> {
|
||||
pub fn message_body<B>(&mut self, body: B) -> Result<HttpResponse<B>, Error> {
|
||||
if let Some(err) = self.err.take() {
|
||||
return HttpResponse::from_error(Error::from(err)).into_body();
|
||||
return Err(err.into());
|
||||
}
|
||||
|
||||
let res = self
|
||||
@ -336,12 +339,12 @@ impl HttpResponseBuilder {
|
||||
for cookie in jar.delta() {
|
||||
match HeaderValue::from_str(&cookie.to_string()) {
|
||||
Ok(val) => res.headers_mut().append(header::SET_COOKIE, val),
|
||||
Err(err) => return HttpResponse::from_error(Error::from(err)).into_body(),
|
||||
Err(err) => return Err(err.into()),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
res
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
/// Set a streaming body and generate `Response`.
|
||||
@ -477,42 +480,42 @@ mod tests {
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_json() {
|
||||
let mut resp = HttpResponse::Ok().json(vec!["v1", "v2", "v3"]);
|
||||
let resp = HttpResponse::Ok().json(vec!["v1", "v2", "v3"]);
|
||||
let ct = resp.headers().get(CONTENT_TYPE).unwrap();
|
||||
assert_eq!(ct, HeaderValue::from_static("application/json"));
|
||||
assert_eq!(
|
||||
body::to_bytes(resp.take_body()).await.unwrap().as_ref(),
|
||||
body::to_bytes(resp.into_body()).await.unwrap().as_ref(),
|
||||
br#"["v1","v2","v3"]"#
|
||||
);
|
||||
|
||||
let mut resp = HttpResponse::Ok().json(&["v1", "v2", "v3"]);
|
||||
let resp = HttpResponse::Ok().json(&["v1", "v2", "v3"]);
|
||||
let ct = resp.headers().get(CONTENT_TYPE).unwrap();
|
||||
assert_eq!(ct, HeaderValue::from_static("application/json"));
|
||||
assert_eq!(
|
||||
body::to_bytes(resp.take_body()).await.unwrap().as_ref(),
|
||||
body::to_bytes(resp.into_body()).await.unwrap().as_ref(),
|
||||
br#"["v1","v2","v3"]"#
|
||||
);
|
||||
|
||||
// content type override
|
||||
let mut resp = HttpResponse::Ok()
|
||||
let resp = HttpResponse::Ok()
|
||||
.insert_header((CONTENT_TYPE, "text/json"))
|
||||
.json(&vec!["v1", "v2", "v3"]);
|
||||
let ct = resp.headers().get(CONTENT_TYPE).unwrap();
|
||||
assert_eq!(ct, HeaderValue::from_static("text/json"));
|
||||
assert_eq!(
|
||||
body::to_bytes(resp.take_body()).await.unwrap().as_ref(),
|
||||
body::to_bytes(resp.into_body()).await.unwrap().as_ref(),
|
||||
br#"["v1","v2","v3"]"#
|
||||
);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_serde_json_in_body() {
|
||||
let mut resp = HttpResponse::Ok().body(
|
||||
let resp = HttpResponse::Ok().body(
|
||||
serde_json::to_vec(&serde_json::json!({ "test-key": "test-value" })).unwrap(),
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
body::to_bytes(resp.take_body()).await.unwrap().as_ref(),
|
||||
body::to_bytes(resp.into_body()).await.unwrap().as_ref(),
|
||||
br#"{"test-key":"test-value"}"#
|
||||
);
|
||||
}
|
||||
|
@ -8,7 +8,7 @@ use std::{
|
||||
};
|
||||
|
||||
use actix_http::{
|
||||
body::{Body, MessageBody, ResponseBody},
|
||||
body::{Body, MessageBody},
|
||||
http::{header::HeaderMap, StatusCode},
|
||||
Extensions, Response, ResponseHead,
|
||||
};
|
||||
@ -27,7 +27,7 @@ use crate::{error::Error, HttpResponseBuilder};
|
||||
/// An HTTP Response
|
||||
pub struct HttpResponse<B = Body> {
|
||||
res: Response<B>,
|
||||
error: Option<Error>,
|
||||
pub(crate) error: Option<Error>,
|
||||
}
|
||||
|
||||
impl HttpResponse<Body> {
|
||||
@ -56,14 +56,6 @@ impl HttpResponse<Body> {
|
||||
error: Some(error),
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert response to response with body
|
||||
pub fn into_body<B>(self) -> HttpResponse<B> {
|
||||
HttpResponse {
|
||||
res: self.res.into_body(),
|
||||
error: self.error,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<B> HttpResponse<B> {
|
||||
@ -192,7 +184,7 @@ impl<B> HttpResponse<B> {
|
||||
|
||||
/// Get body of this response
|
||||
#[inline]
|
||||
pub fn body(&self) -> &ResponseBody<B> {
|
||||
pub fn body(&self) -> &B {
|
||||
self.res.body()
|
||||
}
|
||||
|
||||
@ -206,7 +198,7 @@ impl<B> HttpResponse<B> {
|
||||
}
|
||||
|
||||
/// Split response and body
|
||||
pub fn into_parts(self) -> (HttpResponse<()>, ResponseBody<B>) {
|
||||
pub fn into_parts(self) -> (HttpResponse<()>, B) {
|
||||
let (head, body) = self.res.into_parts();
|
||||
|
||||
(
|
||||
@ -229,7 +221,7 @@ impl<B> HttpResponse<B> {
|
||||
/// Set a body and return previous body value
|
||||
pub fn map_body<F, B2>(self, f: F) -> HttpResponse<B2>
|
||||
where
|
||||
F: FnOnce(&mut ResponseHead, ResponseBody<B>) -> ResponseBody<B2>,
|
||||
F: FnOnce(&mut ResponseHead, B) -> B2,
|
||||
{
|
||||
HttpResponse {
|
||||
res: self.res.map_body(f),
|
||||
@ -238,8 +230,8 @@ impl<B> HttpResponse<B> {
|
||||
}
|
||||
|
||||
/// Extract response body
|
||||
pub fn take_body(&mut self) -> ResponseBody<B> {
|
||||
self.res.take_body()
|
||||
pub fn into_body(self) -> B {
|
||||
self.res.into_body()
|
||||
}
|
||||
}
|
||||
|
||||
@ -274,20 +266,25 @@ impl<B> From<HttpResponse<B>> for Response<B> {
|
||||
|
||||
// TODO: expose cause somewhere?
|
||||
// if let Some(err) = res.error {
|
||||
// eprintln!("impl<B> From<HttpResponse<B>> for Response<B> let Some(err)");
|
||||
// return Response::from_error(err).into_body();
|
||||
// return Response::from_error(err);
|
||||
// }
|
||||
|
||||
res.res
|
||||
}
|
||||
}
|
||||
|
||||
impl Future for HttpResponse {
|
||||
// Future is only implemented for Body payload type because it's the most useful for making simple
|
||||
// handlers without async blocks. Making it generic over all MessageBody types requires a future
|
||||
// impl on Response which would cause it's body field to be, undesirably, Option<B>.
|
||||
//
|
||||
// This impl is not particularly efficient due to the Response construction and should probably
|
||||
// not be invoked if performance is important. Prefer an async fn/block in such cases.
|
||||
impl Future for HttpResponse<Body> {
|
||||
type Output = Result<Response<Body>, Error>;
|
||||
|
||||
fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
|
||||
if let Some(err) = self.error.take() {
|
||||
return Poll::Ready(Ok(Response::from_error(err).into_body()));
|
||||
return Poll::Ready(Err(err));
|
||||
}
|
||||
|
||||
Poll::Ready(Ok(mem::replace(
|
||||
|
@ -578,7 +578,7 @@ mod tests {
|
||||
use actix_utils::future::ok;
|
||||
use bytes::Bytes;
|
||||
|
||||
use crate::dev::{Body, ResponseBody};
|
||||
use crate::dev::Body;
|
||||
use crate::http::{header, HeaderValue, Method, StatusCode};
|
||||
use crate::middleware::DefaultHeaders;
|
||||
use crate::service::ServiceRequest;
|
||||
@ -748,7 +748,7 @@ mod tests {
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
|
||||
match resp.response().body() {
|
||||
ResponseBody::Body(Body::Bytes(ref b)) => {
|
||||
Body::Bytes(ref b) => {
|
||||
let bytes = b.clone();
|
||||
assert_eq!(bytes, Bytes::from_static(b"project: project1"));
|
||||
}
|
||||
@ -849,7 +849,7 @@ mod tests {
|
||||
assert_eq!(resp.status(), StatusCode::CREATED);
|
||||
|
||||
match resp.response().body() {
|
||||
ResponseBody::Body(Body::Bytes(ref b)) => {
|
||||
Body::Bytes(ref b) => {
|
||||
let bytes = b.clone();
|
||||
assert_eq!(bytes, Bytes::from_static(b"project: project_1"));
|
||||
}
|
||||
@ -877,7 +877,7 @@ mod tests {
|
||||
assert_eq!(resp.status(), StatusCode::CREATED);
|
||||
|
||||
match resp.response().body() {
|
||||
ResponseBody::Body(Body::Bytes(ref b)) => {
|
||||
Body::Bytes(ref b) => {
|
||||
let bytes = b.clone();
|
||||
assert_eq!(bytes, Bytes::from_static(b"project: test - 1"));
|
||||
}
|
||||
|
@ -2,7 +2,7 @@ use std::cell::{Ref, RefMut};
|
||||
use std::rc::Rc;
|
||||
use std::{fmt, net};
|
||||
|
||||
use actix_http::body::{Body, MessageBody, ResponseBody};
|
||||
use actix_http::body::{Body, MessageBody};
|
||||
use actix_http::http::{HeaderMap, Method, StatusCode, Uri, Version};
|
||||
use actix_http::{
|
||||
Error, Extensions, HttpMessage, Payload, PayloadStream, RequestHead, Response, ResponseHead,
|
||||
@ -110,9 +110,9 @@ impl ServiceRequest {
|
||||
|
||||
/// Create service response for error
|
||||
#[inline]
|
||||
pub fn error_response<B, E: Into<Error>>(self, err: E) -> ServiceResponse<B> {
|
||||
pub fn error_response<E: Into<Error>>(self, err: E) -> ServiceResponse {
|
||||
let res = HttpResponse::from_error(err.into());
|
||||
ServiceResponse::new(self.req, res.into_body())
|
||||
ServiceResponse::new(self.req, res)
|
||||
}
|
||||
|
||||
/// This method returns reference to the request head
|
||||
@ -335,22 +335,24 @@ pub struct ServiceResponse<B = Body> {
|
||||
response: HttpResponse<B>,
|
||||
}
|
||||
|
||||
impl ServiceResponse<Body> {
|
||||
/// Create service response from the error
|
||||
pub fn from_err<E: Into<Error>>(err: E, request: HttpRequest) -> Self {
|
||||
let response = HttpResponse::from_error(err.into());
|
||||
ServiceResponse { request, response }
|
||||
}
|
||||
}
|
||||
|
||||
impl<B> ServiceResponse<B> {
|
||||
/// Create service response instance
|
||||
pub fn new(request: HttpRequest, response: HttpResponse<B>) -> Self {
|
||||
ServiceResponse { request, response }
|
||||
}
|
||||
|
||||
/// Create service response from the error
|
||||
pub fn from_err<E: Into<Error>>(err: E, request: HttpRequest) -> Self {
|
||||
let response = HttpResponse::from_error(err.into()).into_body();
|
||||
ServiceResponse { request, response }
|
||||
}
|
||||
|
||||
/// Create service response for error
|
||||
#[inline]
|
||||
pub fn error_response<E: Into<Error>>(self, err: E) -> Self {
|
||||
Self::from_err(err, self.request)
|
||||
pub fn error_response<E: Into<Error>>(self, err: E) -> ServiceResponse {
|
||||
ServiceResponse::from_err(err, self.request)
|
||||
}
|
||||
|
||||
/// Create service response
|
||||
@ -396,23 +398,18 @@ impl<B> ServiceResponse<B> {
|
||||
}
|
||||
|
||||
/// Execute closure and in case of error convert it to response.
|
||||
pub fn checked_expr<F, E>(mut self, f: F) -> Self
|
||||
pub fn checked_expr<F, E>(mut self, f: F) -> Result<Self, Error>
|
||||
where
|
||||
F: FnOnce(&mut Self) -> Result<(), E>,
|
||||
E: Into<Error>,
|
||||
{
|
||||
match f(&mut self) {
|
||||
Ok(_) => self,
|
||||
Err(err) => {
|
||||
let res = HttpResponse::from_error(err.into());
|
||||
ServiceResponse::new(self.request, res.into_body())
|
||||
}
|
||||
}
|
||||
f(&mut self).map_err(Into::into)?;
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Extract response body
|
||||
pub fn take_body(&mut self) -> ResponseBody<B> {
|
||||
self.response.take_body()
|
||||
pub fn into_body(self) -> B {
|
||||
self.response.into_body()
|
||||
}
|
||||
}
|
||||
|
||||
@ -420,7 +417,7 @@ impl<B> ServiceResponse<B> {
|
||||
/// Set a new body
|
||||
pub fn map_body<F, B2>(self, f: F) -> ServiceResponse<B2>
|
||||
where
|
||||
F: FnOnce(&mut ResponseHead, ResponseBody<B>) -> ResponseBody<B2>,
|
||||
F: FnOnce(&mut ResponseHead, B) -> B2,
|
||||
{
|
||||
let response = self.response.map_body(f);
|
||||
|
||||
|
31
src/test.rs
31
src/test.rs
@ -4,13 +4,14 @@ use std::{net::SocketAddr, rc::Rc};
|
||||
|
||||
pub use actix_http::test::TestBuffer;
|
||||
use actix_http::{
|
||||
body,
|
||||
http::{header::IntoHeaderPair, Method, StatusCode, Uri, Version},
|
||||
test::TestRequest as HttpTestRequest,
|
||||
Extensions, Request,
|
||||
};
|
||||
use actix_router::{Path, ResourceDef, Url};
|
||||
use actix_service::{IntoService, IntoServiceFactory, Service, ServiceFactory};
|
||||
use actix_utils::future::ok;
|
||||
use actix_utils::future::{ok, poll_fn};
|
||||
use futures_core::Stream;
|
||||
use futures_util::StreamExt as _;
|
||||
use serde::{de::DeserializeOwned, Serialize};
|
||||
@ -153,16 +154,17 @@ where
|
||||
B: MessageBody + Unpin,
|
||||
B::Error: Into<Error>,
|
||||
{
|
||||
let mut resp = app
|
||||
let resp = app
|
||||
.call(req)
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("read_response failed at application call: {}", e));
|
||||
|
||||
let mut body = resp.take_body();
|
||||
let body = resp.into_body();
|
||||
let mut bytes = BytesMut::new();
|
||||
|
||||
while let Some(item) = body.next().await {
|
||||
bytes.extend_from_slice(&item.unwrap());
|
||||
actix_rt::pin!(body);
|
||||
while let Some(item) = poll_fn(|cx| body.as_mut().poll_next(cx)).await {
|
||||
bytes.extend_from_slice(&item.map_err(Into::into).unwrap());
|
||||
}
|
||||
|
||||
bytes.freeze()
|
||||
@ -194,16 +196,19 @@ where
|
||||
/// assert_eq!(result, Bytes::from_static(b"welcome!"));
|
||||
/// }
|
||||
/// ```
|
||||
pub async fn read_body<B>(mut res: ServiceResponse<B>) -> Bytes
|
||||
pub async fn read_body<B>(res: ServiceResponse<B>) -> Bytes
|
||||
where
|
||||
B: MessageBody + Unpin,
|
||||
B::Error: Into<Error>,
|
||||
{
|
||||
let mut body = res.take_body();
|
||||
let body = res.into_body();
|
||||
let mut bytes = BytesMut::new();
|
||||
while let Some(item) = body.next().await {
|
||||
bytes.extend_from_slice(&item.unwrap());
|
||||
|
||||
actix_rt::pin!(body);
|
||||
while let Some(item) = poll_fn(|cx| body.as_mut().poll_next(cx)).await {
|
||||
bytes.extend_from_slice(&item.map_err(Into::into).unwrap());
|
||||
}
|
||||
|
||||
bytes.freeze()
|
||||
}
|
||||
|
||||
@ -271,6 +276,14 @@ where
|
||||
Ok(data.freeze())
|
||||
}
|
||||
|
||||
pub async fn load_body<B>(body: B) -> Result<Bytes, Error>
|
||||
where
|
||||
B: MessageBody + Unpin,
|
||||
B::Error: Into<Error>,
|
||||
{
|
||||
body::to_bytes(body).await.map_err(Into::into)
|
||||
}
|
||||
|
||||
/// Helper function that returns a deserialized response body of a TestRequest
|
||||
///
|
||||
/// ```
|
||||
|
@ -435,7 +435,7 @@ mod tests {
|
||||
header::{self, CONTENT_LENGTH, CONTENT_TYPE},
|
||||
StatusCode,
|
||||
},
|
||||
test::{load_stream, TestRequest},
|
||||
test::{load_body, TestRequest},
|
||||
};
|
||||
|
||||
#[derive(Serialize, Deserialize, PartialEq, Debug)]
|
||||
@ -492,10 +492,10 @@ mod tests {
|
||||
.to_http_parts();
|
||||
|
||||
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
|
||||
let mut resp = HttpResponse::from_error(s.err().unwrap());
|
||||
let resp = HttpResponse::from_error(s.err().unwrap());
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
|
||||
let body = load_stream(resp.take_body()).await.unwrap();
|
||||
let body = load_body(resp.into_body()).await.unwrap();
|
||||
let msg: MyObject = serde_json::from_slice(&body).unwrap();
|
||||
assert_eq!(msg.name, "invalid request");
|
||||
}
|
||||
|
Reference in New Issue
Block a user