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

body ergonomics v3 (#2468)

This commit is contained in:
Rob Ede
2021-12-04 19:40:47 +00:00
committed by GitHub
parent a2d5c5a058
commit c7c02ef99d
84 changed files with 2134 additions and 1685 deletions

View File

@@ -8,7 +8,7 @@ use std::{
};
use actix_http::{
body::{AnyBody, MessageBody},
body::{BoxBody, EitherBody, MessageBody},
http::{header::HeaderMap, StatusCode},
Extensions, Response, ResponseHead,
};
@@ -25,12 +25,12 @@ use {
use crate::{error::Error, HttpResponseBuilder};
/// An outgoing response.
pub struct HttpResponse<B = AnyBody> {
pub struct HttpResponse<B = BoxBody> {
res: Response<B>,
pub(crate) error: Option<Error>,
}
impl HttpResponse<AnyBody> {
impl HttpResponse<BoxBody> {
/// Constructs a response.
#[inline]
pub fn new(status: StatusCode) -> Self {
@@ -227,8 +227,26 @@ impl<B> HttpResponse<B> {
}
}
// TODO: into_body equivalent
// TODO: into_boxed_body
// TODO: docs for the body map methods below
#[inline]
pub fn map_into_left_body<R>(self) -> HttpResponse<EitherBody<B, R>> {
self.map_body(|_, body| EitherBody::left(body))
}
#[inline]
pub fn map_into_right_body<L>(self) -> HttpResponse<EitherBody<L, B>> {
self.map_body(|_, body| EitherBody::right(body))
}
#[inline]
pub fn map_into_boxed_body(self) -> HttpResponse<BoxBody>
where
B: MessageBody + 'static,
{
// TODO: avoid double boxing with down-casting, if it improves perf
self.map_body(|_, body| BoxBody::new(body))
}
/// Extract response body
pub fn into_body(self) -> B {
@@ -273,14 +291,14 @@ impl<B> From<HttpResponse<B>> for Response<B> {
}
}
// Future is only implemented for AnyBody payload type because it's the most useful for making
// Future is only implemented for BoxBody 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<AnyBody> {
type Output = Result<Response<AnyBody>, Error>;
impl Future for HttpResponse<BoxBody> {
type Output = Result<Response<BoxBody>, Error>;
fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
if let Some(err) = self.error.take() {