1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-05-20 01:08:10 +00:00

remove internal usage of Body

This commit is contained in:
Rob Ede 2021-11-16 22:10:30 +00:00
parent d8cbb879dd
commit 668a33c793
No known key found for this signature in database
GPG key ID: 97C636207D3EF933
23 changed files with 137 additions and 111 deletions

View file

@ -1,12 +1,12 @@
use std::io;
use actix_http::{body::Body, http::HeaderValue, http::StatusCode};
use actix_http::{body::AnyBody, http::HeaderValue, http::StatusCode};
use actix_http::{Error, HttpService, Request, Response};
use actix_server::Server;
use bytes::BytesMut;
use futures_util::StreamExt as _;
async fn handle_request(mut req: Request) -> Result<Response<Body>, Error> {
async fn handle_request(mut req: Request) -> Result<Response<AnyBody>, Error> {
let mut body = BytesMut::new();
while let Some(item) = req.payload().next().await {
body.extend_from_slice(&item?)

View file

@ -14,6 +14,7 @@ use crate::error::Error;
use super::{BodySize, BodyStream, MessageBody, MessageBodyMapErr, SizedStream};
#[deprecated(since = "4.0.0", note = "Renamed to `AnyBody`.")]
pub type Body = AnyBody;
/// Represents various types of HTTP message body.
@ -116,7 +117,7 @@ where
}
impl PartialEq for AnyBody {
fn eq(&self, other: &Body) -> bool {
fn eq(&self, other: &AnyBody) -> bool {
match *self {
AnyBody::None => matches!(*other, AnyBody::None),
AnyBody::Bytes(ref b) => match *other {
@ -139,37 +140,37 @@ impl<S: fmt::Debug> fmt::Debug for AnyBody<S> {
}
impl From<&'static str> for AnyBody {
fn from(string: &'static str) -> Body {
fn from(string: &'static str) -> AnyBody {
AnyBody::Bytes(Bytes::from_static(string.as_ref()))
}
}
impl From<&'static [u8]> for AnyBody {
fn from(bytes: &'static [u8]) -> Body {
fn from(bytes: &'static [u8]) -> AnyBody {
AnyBody::Bytes(Bytes::from_static(bytes))
}
}
impl From<Vec<u8>> for AnyBody {
fn from(vec: Vec<u8>) -> Body {
fn from(vec: Vec<u8>) -> AnyBody {
AnyBody::Bytes(Bytes::from(vec))
}
}
impl From<String> for AnyBody {
fn from(string: String) -> Body {
fn from(string: String) -> AnyBody {
string.into_bytes().into()
}
}
impl From<&'_ String> for AnyBody {
fn from(string: &String) -> Body {
fn from(string: &String) -> AnyBody {
AnyBody::Bytes(Bytes::copy_from_slice(AsRef::<[u8]>::as_ref(&string)))
}
}
impl From<Cow<'_, str>> for AnyBody {
fn from(string: Cow<'_, str>) -> Body {
fn from(string: Cow<'_, str>) -> AnyBody {
match string {
Cow::Owned(s) => AnyBody::from(s),
Cow::Borrowed(s) => {
@ -180,33 +181,53 @@ impl From<Cow<'_, str>> for AnyBody {
}
impl From<Bytes> for AnyBody {
fn from(bytes: Bytes) -> Body {
fn from(bytes: Bytes) -> Self {
AnyBody::Bytes(bytes)
}
}
impl From<BytesMut> for AnyBody {
fn from(bytes: BytesMut) -> Body {
fn from(bytes: BytesMut) -> Self {
AnyBody::Bytes(bytes.freeze())
}
}
impl<S, E> From<SizedStream<S>> for AnyBody<SizedStream<S>>
where
S: Stream<Item = Result<Bytes, E>> + 'static,
E: Into<Box<dyn StdError>> + 'static,
{
fn from(stream: SizedStream<S>) -> Self {
AnyBody::new(stream)
}
}
impl<S, E> From<SizedStream<S>> for AnyBody
where
S: Stream<Item = Result<Bytes, E>> + 'static,
E: Into<Box<dyn StdError>> + 'static,
{
fn from(stream: SizedStream<S>) -> Body {
fn from(stream: SizedStream<S>) -> Self {
AnyBody::new_boxed(stream)
}
}
impl<S, E> From<BodyStream<S>> for AnyBody<BodyStream<S>>
where
S: Stream<Item = Result<Bytes, E>> + 'static,
E: Into<Box<dyn StdError>> + 'static,
{
fn from(stream: BodyStream<S>) -> Self {
AnyBody::new(stream)
}
}
impl<S, E> From<BodyStream<S>> for AnyBody
where
S: Stream<Item = Result<Bytes, E>> + 'static,
E: Into<Box<dyn StdError>> + 'static,
{
fn from(stream: BodyStream<S>) -> Body {
fn from(stream: BodyStream<S>) -> Self {
AnyBody::new_boxed(stream)
}
}

View file

@ -14,6 +14,7 @@ mod message_body;
mod size;
mod sized_stream;
#[allow(deprecated)]
pub use self::body::{AnyBody, Body, BoxBody};
pub use self::body_stream::BodyStream;
pub use self::message_body::MessageBody;
@ -76,10 +77,10 @@ mod tests {
use super::*;
impl Body {
impl AnyBody {
pub(crate) fn get_ref(&self) -> &[u8] {
match *self {
Body::Bytes(ref bin) => bin,
AnyBody::Bytes(ref bin) => bin,
_ => panic!(),
}
}
@ -87,9 +88,9 @@ mod tests {
#[actix_rt::test]
async fn test_static_str() {
assert_eq!(Body::from("").size(), BodySize::Sized(0));
assert_eq!(Body::from("test").size(), BodySize::Sized(4));
assert_eq!(Body::from("test").get_ref(), b"test");
assert_eq!(AnyBody::from("").size(), BodySize::Sized(0));
assert_eq!(AnyBody::from("test").size(), BodySize::Sized(4));
assert_eq!(AnyBody::from("test").get_ref(), b"test");
assert_eq!("test".size(), BodySize::Sized(4));
assert_eq!(
@ -103,13 +104,16 @@ mod tests {
#[actix_rt::test]
async fn test_static_bytes() {
assert_eq!(Body::from(b"test".as_ref()).size(), BodySize::Sized(4));
assert_eq!(Body::from(b"test".as_ref()).get_ref(), b"test");
assert_eq!(AnyBody::from(b"test".as_ref()).size(), BodySize::Sized(4));
assert_eq!(AnyBody::from(b"test".as_ref()).get_ref(), b"test");
assert_eq!(
Body::copy_from_slice(b"test".as_ref()).size(),
AnyBody::copy_from_slice(b"test".as_ref()).size(),
BodySize::Sized(4)
);
assert_eq!(Body::copy_from_slice(b"test".as_ref()).get_ref(), b"test");
assert_eq!(
AnyBody::copy_from_slice(b"test".as_ref()).get_ref(),
b"test"
);
let sb = Bytes::from(&b"test"[..]);
pin!(sb);
@ -122,8 +126,8 @@ mod tests {
#[actix_rt::test]
async fn test_vec() {
assert_eq!(Body::from(Vec::from("test")).size(), BodySize::Sized(4));
assert_eq!(Body::from(Vec::from("test")).get_ref(), b"test");
assert_eq!(AnyBody::from(Vec::from("test")).size(), BodySize::Sized(4));
assert_eq!(AnyBody::from(Vec::from("test")).get_ref(), b"test");
let test_vec = Vec::from("test");
pin!(test_vec);
@ -140,8 +144,8 @@ mod tests {
#[actix_rt::test]
async fn test_bytes() {
let b = Bytes::from("test");
assert_eq!(Body::from(b.clone()).size(), BodySize::Sized(4));
assert_eq!(Body::from(b.clone()).get_ref(), b"test");
assert_eq!(AnyBody::from(b.clone()).size(), BodySize::Sized(4));
assert_eq!(AnyBody::from(b.clone()).get_ref(), b"test");
pin!(b);
assert_eq!(b.size(), BodySize::Sized(4));
@ -154,8 +158,8 @@ mod tests {
#[actix_rt::test]
async fn test_bytes_mut() {
let b = BytesMut::from("test");
assert_eq!(Body::from(b.clone()).size(), BodySize::Sized(4));
assert_eq!(Body::from(b.clone()).get_ref(), b"test");
assert_eq!(AnyBody::from(b.clone()).size(), BodySize::Sized(4));
assert_eq!(AnyBody::from(b.clone()).get_ref(), b"test");
pin!(b);
assert_eq!(b.size(), BodySize::Sized(4));
@ -168,10 +172,10 @@ mod tests {
#[actix_rt::test]
async fn test_string() {
let b = "test".to_owned();
assert_eq!(Body::from(b.clone()).size(), BodySize::Sized(4));
assert_eq!(Body::from(b.clone()).get_ref(), b"test");
assert_eq!(Body::from(&b).size(), BodySize::Sized(4));
assert_eq!(Body::from(&b).get_ref(), b"test");
assert_eq!(AnyBody::from(b.clone()).size(), BodySize::Sized(4));
assert_eq!(AnyBody::from(b.clone()).get_ref(), b"test");
assert_eq!(AnyBody::from(&b).size(), BodySize::Sized(4));
assert_eq!(AnyBody::from(&b).get_ref(), b"test");
pin!(b);
assert_eq!(b.size(), BodySize::Sized(4));
@ -204,29 +208,33 @@ mod tests {
#[actix_rt::test]
async fn test_body_eq() {
assert!(
Body::Bytes(Bytes::from_static(b"1"))
== Body::Bytes(Bytes::from_static(b"1"))
AnyBody::Bytes(Bytes::from_static(b"1"))
== AnyBody::Bytes(Bytes::from_static(b"1"))
);
assert!(Body::Bytes(Bytes::from_static(b"1")) != Body::None);
assert!(AnyBody::Bytes(Bytes::from_static(b"1")) != AnyBody::None);
}
#[actix_rt::test]
async fn test_body_debug() {
assert!(format!("{:?}", Body::None).contains("Body::None"));
assert!(format!("{:?}", Body::Bytes(Bytes::from_static(b"1"))).contains('1'));
assert!(format!("{:?}", AnyBody::<BoxBody>::None).contains("Body::None"));
assert!(format!("{:?}", AnyBody::from(Bytes::from_static(b"1"))).contains('1'));
}
#[actix_rt::test]
async fn test_serde_json() {
use serde_json::{json, Value};
assert_eq!(
Body::from(serde_json::to_vec(&Value::String("test".to_owned())).unwrap())
.size(),
AnyBody::from(
serde_json::to_vec(&Value::String("test".to_owned())).unwrap()
)
.size(),
BodySize::Sized(6)
);
assert_eq!(
Body::from(serde_json::to_vec(&json!({"test-key":"test-value"})).unwrap())
.size(),
AnyBody::from(
serde_json::to_vec(&json!({"test-key":"test-value"})).unwrap()
)
.size(),
BodySize::Sized(25)
);
}
@ -250,11 +258,11 @@ mod tests {
#[actix_rt::test]
async fn test_to_bytes() {
let body = Body::empty();
let body = AnyBody::empty();
let bytes = to_bytes(body).await.unwrap();
assert!(bytes.is_empty());
let body = Body::Bytes(Bytes::from_static(b"123"));
let body = AnyBody::copy_from_slice(b"123");
let bytes = to_bytes(body).await.unwrap();
assert_eq!(bytes, b"123"[..]);
}

View file

@ -5,10 +5,7 @@ use std::{error::Error as StdError, fmt, io, str::Utf8Error, string::FromUtf8Err
use derive_more::{Display, Error, From};
use http::{uri::InvalidUri, StatusCode};
use crate::{
body::{AnyBody, Body},
ws, Response,
};
use crate::{body::AnyBody, ws, Response};
pub use http::Error as HttpError;
@ -29,6 +26,11 @@ impl Error {
}
}
pub(crate) fn with_cause(mut self, cause: impl Into<Box<dyn StdError>>) -> Self {
self.inner.cause = Some(cause.into());
self
}
pub(crate) fn new_http() -> Self {
Self::new(Kind::Http)
}
@ -49,14 +51,12 @@ impl Error {
Self::new(Kind::SendResponse)
}
// TODO: remove allow
#[allow(dead_code)]
#[allow(unused)] // reserved for future use (TODO: remove allow when being used)
pub(crate) fn new_io() -> Self {
Self::new(Kind::Io)
}
// used in encoder behind feature flag so ignore unused warning
#[allow(unused)]
#[allow(unused)] // used in encoder behind feature flag so ignore unused warning
pub(crate) fn new_encoder() -> Self {
Self::new(Kind::Encoder)
}
@ -64,11 +64,6 @@ impl Error {
pub(crate) fn new_ws() -> Self {
Self::new(Kind::Ws)
}
pub(crate) fn with_cause(mut self, cause: impl Into<Box<dyn StdError>>) -> Self {
self.inner.cause = Some(cause.into());
self
}
}
impl From<Error> for Response<AnyBody> {
@ -78,12 +73,12 @@ impl From<Error> for Response<AnyBody> {
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
Response::new(status_code).set_body(Body::from(err.to_string()))
Response::new(status_code).set_body(AnyBody::from(err.to_string()))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
pub enum Kind {
pub(crate) enum Kind {
#[display(fmt = "error processing HTTP")]
Http,

View file

@ -195,6 +195,7 @@ mod tests {
use super::*;
// copy of encoding from actix-web headers
#[allow(clippy::enum_variant_names)] // allow Encoding prefix on EncodingExt
#[derive(Clone, PartialEq, Debug)]
pub enum Encoding {
Chunked,

View file

@ -357,7 +357,7 @@ impl fmt::Debug for ResponseBuilder {
#[cfg(test)]
mod tests {
use super::*;
use crate::body::Body;
use crate::body::AnyBody;
use crate::http::header::{HeaderName, HeaderValue, CONTENT_TYPE};
#[test]
@ -390,13 +390,13 @@ mod tests {
fn test_content_type() {
let resp = Response::build(StatusCode::OK)
.content_type("text/plain")
.body(Body::empty());
.body(AnyBody::empty());
assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "text/plain")
}
#[test]
fn test_into_builder() {
let mut resp: Response<Body> = "test".into();
let mut resp: Response<AnyBody> = "test".into();
assert_eq!(resp.status(), StatusCode::OK);
resp.headers_mut().insert(

View file

@ -5,7 +5,7 @@ extern crate tls_openssl as openssl;
use std::{convert::Infallible, io};
use actix_http::{
body::{AnyBody, Body, SizedStream},
body::{AnyBody, SizedStream},
error::PayloadError,
http::{
header::{self, HeaderValue},
@ -409,7 +409,7 @@ impl From<BadRequest> for Response<AnyBody> {
async fn test_h2_service_error() {
let mut srv = test_server(move || {
HttpService::build()
.h2(|_| err::<Response<Body>, _>(BadRequest))
.h2(|_| err::<Response<AnyBody>, _>(BadRequest))
.openssl(tls_config())
.map_err(|_| ())
})

View file

@ -10,7 +10,7 @@ use std::{
};
use actix_http::{
body::{AnyBody, Body, SizedStream},
body::{AnyBody, SizedStream},
error::PayloadError,
http::{
header::{self, HeaderName, HeaderValue},
@ -477,7 +477,7 @@ impl From<BadRequest> for Response<AnyBody> {
async fn test_h2_service_error() {
let mut srv = test_server(move || {
HttpService::build()
.h2(|_| err::<Response<Body>, _>(BadRequest))
.h2(|_| err::<Response<AnyBody>, _>(BadRequest))
.rustls(tls_config())
})
.await;
@ -494,7 +494,7 @@ async fn test_h2_service_error() {
async fn test_h1_service_error() {
let mut srv = test_server(move || {
HttpService::build()
.h1(|_| err::<Response<Body>, _>(BadRequest))
.h1(|_| err::<Response<AnyBody>, _>(BadRequest))
.rustls(tls_config())
})
.await;

View file

@ -6,7 +6,7 @@ use std::{
};
use actix_http::{
body::{AnyBody, Body, SizedStream},
body::{AnyBody, SizedStream},
header, http, Error, HttpMessage, HttpService, KeepAlive, Request, Response,
StatusCode,
};
@ -724,7 +724,7 @@ impl From<BadRequest> for Response<AnyBody> {
async fn test_h1_service_error() {
let mut srv = test_server(|| {
HttpService::build()
.h1(|_| err::<Response<Body>, _>(BadRequest))
.h1(|_| err::<Response<AnyBody>, _>(BadRequest))
.tcp()
})
.await;

View file

@ -8,7 +8,7 @@ use std::{
use actix_codec::Framed;
use actix_http::{
body::Body, h1::ClientCodec, Payload, RequestHead, RequestHeadType, ResponseHead,
body::AnyBody, h1::ClientCodec, Payload, RequestHead, RequestHeadType, ResponseHead,
};
use actix_service::Service;
use futures_core::{future::LocalBoxFuture, ready};
@ -30,7 +30,7 @@ pub type BoxConnectorService = Rc<
pub type BoxedSocket = Box<dyn ConnectionIo>;
pub enum ConnectRequest {
Client(RequestHeadType, Body, Option<net::SocketAddr>),
Client(RequestHeadType, AnyBody, Option<net::SocketAddr>),
Tunnel(RequestHead, Option<net::SocketAddr>),
}

View file

@ -5,7 +5,7 @@ use futures_core::Stream;
use serde::Serialize;
use actix_http::{
body::Body,
body::AnyBody,
http::{header::IntoHeaderValue, Error as HttpError, HeaderMap, HeaderName, Method, Uri},
RequestHead,
};
@ -45,7 +45,7 @@ impl FrozenClientRequest {
/// Send a body.
pub fn send_body<B>(&self, body: B) -> SendClientRequest
where
B: Into<Body>,
B: Into<AnyBody>,
{
RequestSender::Rc(self.head.clone(), None).send_body(
self.addr,
@ -158,7 +158,7 @@ impl FrozenSendBuilder {
/// Complete request construction and send a body.
pub fn send_body<B>(self, body: B) -> SendClientRequest
where
B: Into<Body>,
B: Into<AnyBody>,
{
if let Some(e) = self.err {
return e.into();

View file

@ -8,7 +8,7 @@ use std::{
};
use actix_http::{
body::Body,
body::AnyBody,
http::{header, Method, StatusCode, Uri},
RequestHead, RequestHeadType,
};
@ -95,7 +95,7 @@ where
};
let body_opt = match body {
Body::Bytes(ref b) => Some(b.clone()),
AnyBody::Bytes(ref b) => Some(b.clone()),
_ => None,
};
@ -192,14 +192,14 @@ where
let body_new = if is_redirect {
// try to reuse body
match body {
Some(ref bytes) => Body::Bytes(bytes.clone()),
// TODO: should this be Body::Empty or Body::None.
_ => Body::empty(),
Some(ref bytes) => AnyBody::Bytes(bytes.clone()),
// TODO: should this be AnyBody::Empty or AnyBody::None.
_ => AnyBody::empty(),
}
} else {
body = None;
// remove body
Body::None
AnyBody::None
};
let mut headers = headers.take().unwrap();

View file

@ -5,7 +5,7 @@ use futures_core::Stream;
use serde::Serialize;
use actix_http::{
body::Body,
body::AnyBody,
http::{
header::{self, IntoHeaderPair},
ConnectionType, Error as HttpError, HeaderMap, HeaderValue, Method, Uri, Version,
@ -350,7 +350,7 @@ impl ClientRequest {
/// Complete request construction and send body.
pub fn send_body<B>(self, body: B) -> SendClientRequest
where
B: Into<Body>,
B: Into<AnyBody>,
{
let slf = match self.prep_for_sending() {
Ok(slf) => slf,

View file

@ -9,7 +9,7 @@ use std::{
};
use actix_http::{
body::{AnyBody, Body, BodyStream},
body::{AnyBody, BodyStream},
http::{
header::{self, HeaderMap, HeaderName, IntoHeaderValue},
Error as HttpError,
@ -196,7 +196,7 @@ impl RequestSender {
body: B,
) -> SendClientRequest
where
B: Into<Body>,
B: Into<AnyBody>,
{
let req = match self {
RequestSender::Owned(head) => {
@ -236,7 +236,7 @@ impl RequestSender {
response_decompress,
timeout,
config,
Body::Bytes(Bytes::from(body)),
AnyBody::Bytes(Bytes::from(body)),
)
}
@ -265,7 +265,7 @@ impl RequestSender {
response_decompress,
timeout,
config,
Body::Bytes(Bytes::from(body)),
AnyBody::Bytes(Bytes::from(body)),
)
}
@ -297,7 +297,7 @@ impl RequestSender {
timeout: Option<Duration>,
config: &ClientConfig,
) -> SendClientRequest {
self.send_body(addr, response_decompress, timeout, config, Body::empty())
self.send_body(addr, response_decompress, timeout, config, AnyBody::empty())
}
fn set_header_if_none<V>(&mut self, key: HeaderName, value: V) -> Result<(), HttpError>

View file

@ -4,7 +4,7 @@ use std::future::Future;
use std::marker::PhantomData;
use std::rc::Rc;
use actix_http::body::{Body, MessageBody};
use actix_http::body::{AnyBody, MessageBody};
use actix_http::{Extensions, Request};
use actix_service::boxed::{self, BoxServiceFactory};
use actix_service::{
@ -39,7 +39,7 @@ pub struct App<T, B> {
_phantom: PhantomData<B>,
}
impl App<AppEntry, Body> {
impl App<AppEntry, AnyBody> {
/// Create application builder. Application can be configured with a builder-like pattern.
#[allow(clippy::new_without_default)]
pub fn new() -> Self {

View file

@ -14,6 +14,7 @@ pub use crate::types::form::UrlEncoded;
pub use crate::types::json::JsonBody;
pub use crate::types::readlines::Readlines;
#[allow(deprecated)]
pub use actix_http::body::{AnyBody, Body, BodySize, MessageBody, SizedStream};
#[cfg(feature = "__compress")]

View file

@ -1,6 +1,6 @@
use std::{cell::RefCell, fmt, io::Write as _};
use actix_http::{body::Body, header, StatusCode};
use actix_http::{body::AnyBody, header, StatusCode};
use bytes::{BufMut as _, BytesMut};
use crate::{Error, HttpRequest, HttpResponse, Responder, ResponseError};
@ -88,7 +88,7 @@ where
header::CONTENT_TYPE,
header::HeaderValue::from_static("text/plain; charset=utf-8"),
);
res.set_body(Body::from(buf.into_inner()))
res.set_body(AnyBody::from(buf.into_inner()))
}
InternalErrorType::Response(ref resp) => {

View file

@ -1,7 +1,7 @@
use std::borrow::Cow;
use actix_http::{
body::Body,
body::AnyBody,
http::{header::IntoHeaderPair, Error as HttpError, HeaderMap, StatusCode},
};
use bytes::{Bytes, BytesMut};
@ -65,7 +65,7 @@ impl Responder for HttpResponse {
}
}
impl Responder for actix_http::Response<Body> {
impl Responder for actix_http::Response<AnyBody> {
#[inline]
fn respond_to(self, _: &HttpRequest) -> HttpResponse {
HttpResponse::from(self)
@ -254,7 +254,7 @@ pub(crate) mod tests {
let resp = srv.call(req).await.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
match resp.response().body() {
Body::Bytes(ref b) => {
AnyBody::Bytes(ref b) => {
let bytes = b.clone();
assert_eq!(bytes, Bytes::from_static(b"some"));
}
@ -267,14 +267,14 @@ pub(crate) mod tests {
fn body(&self) -> &AnyBody;
}
impl BodyTest for Body {
impl BodyTest for AnyBody {
fn bin_ref(&self) -> &[u8] {
match self {
AnyBody::Bytes(ref bin) => bin,
_ => unreachable!("bug in test impl"),
}
}
fn body(&self) -> &Body {
fn body(&self) -> &AnyBody {
self
}
}

View file

@ -436,7 +436,7 @@ mod tests {
use super::*;
use crate::{
dev::Body,
dev::AnyBody,
http::{
header::{self, HeaderValue, CONTENT_TYPE},
StatusCode,
@ -475,7 +475,7 @@ mod tests {
fn test_content_type() {
let resp = HttpResponseBuilder::new(StatusCode::OK)
.content_type("text/plain")
.body(Body::empty());
.body(AnyBody::empty());
assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "text/plain")
}

View file

@ -8,7 +8,7 @@ use std::{
};
use actix_http::{
body::{AnyBody, Body, MessageBody},
body::{AnyBody, MessageBody},
http::{header::HeaderMap, StatusCode},
Extensions, Response, ResponseHead,
};
@ -273,14 +273,14 @@ impl<B> From<HttpResponse<B>> for Response<B> {
}
}
// 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>.
// Future is only implemented for AnyBody 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>;
impl Future for HttpResponse<AnyBody> {
type Output = Result<Response<AnyBody>, Error>;
fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
if let Some(err) = self.error.take() {

View file

@ -580,7 +580,7 @@ mod tests {
use bytes::Bytes;
use crate::{
dev::Body,
dev::AnyBody,
guard,
http::{header, HeaderValue, Method, StatusCode},
middleware::DefaultHeaders,
@ -752,7 +752,7 @@ mod tests {
assert_eq!(resp.status(), StatusCode::OK);
match resp.response().body() {
Body::Bytes(ref b) => {
AnyBody::Bytes(ref b) => {
let bytes = b.clone();
assert_eq!(bytes, Bytes::from_static(b"project: project1"));
}
@ -853,7 +853,7 @@ mod tests {
assert_eq!(resp.status(), StatusCode::CREATED);
match resp.response().body() {
Body::Bytes(ref b) => {
AnyBody::Bytes(ref b) => {
let bytes = b.clone();
assert_eq!(bytes, Bytes::from_static(b"project: project_1"));
}
@ -881,7 +881,7 @@ mod tests {
assert_eq!(resp.status(), StatusCode::CREATED);
match resp.response().body() {
Body::Bytes(ref b) => {
AnyBody::Bytes(ref b) => {
let bytes = b.clone();
assert_eq!(bytes, Bytes::from_static(b"project: test - 1"));
}

View file

@ -22,7 +22,7 @@ use crate::{
app_service::AppInitServiceState,
config::AppConfig,
data::Data,
dev::{Body, MessageBody, Payload},
dev::{AnyBody, MessageBody, Payload},
http::header::ContentType,
rmap::ResourceMap,
service::{ServiceRequest, ServiceResponse},
@ -32,14 +32,14 @@ use crate::{
/// Create service that always responds with `HttpResponse::Ok()` and no body.
pub fn ok_service(
) -> impl Service<ServiceRequest, Response = ServiceResponse<Body>, Error = Error> {
) -> impl Service<ServiceRequest, Response = ServiceResponse<AnyBody>, Error = Error> {
default_service(StatusCode::OK)
}
/// Create service that always responds with given status code and no body.
pub fn default_service(
status_code: StatusCode,
) -> impl Service<ServiceRequest, Response = ServiceResponse<Body>, Error = Error> {
) -> impl Service<ServiceRequest, Response = ServiceResponse<AnyBody>, Error = Error> {
(move |req: ServiceRequest| {
ok(req.into_response(HttpResponseBuilder::new(status_code).finish()))
})

View file

@ -200,7 +200,7 @@ async fn test_body_encoding_override() {
.body(STR)
})))
.service(web::resource("/raw").route(web::to(|| {
let body = actix_web::dev::Body::Bytes(STR.into());
let body = actix_web::dev::AnyBody::Bytes(STR.into());
let mut response =
HttpResponse::with_body(actix_web::http::StatusCode::OK, body);