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

remove responsebody indirection from response (#2201)

This commit is contained in:
Rob Ede
2021-05-09 20:12:48 +01:00
committed by GitHub
parent a9dc1586a0
commit 900c9e270e
31 changed files with 381 additions and 263 deletions

View File

@@ -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"}"#
);
}

View File

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