1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-06-02 21:39:26 +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 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_http::{Error, HttpService, Request, Response};
use actix_server::Server; use actix_server::Server;
use bytes::BytesMut; use bytes::BytesMut;
use futures_util::StreamExt as _; 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(); let mut body = BytesMut::new();
while let Some(item) = req.payload().next().await { while let Some(item) = req.payload().next().await {
body.extend_from_slice(&item?) body.extend_from_slice(&item?)

View file

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

View file

@ -14,6 +14,7 @@ mod message_body;
mod size; mod size;
mod sized_stream; mod sized_stream;
#[allow(deprecated)]
pub use self::body::{AnyBody, Body, BoxBody}; pub use self::body::{AnyBody, Body, BoxBody};
pub use self::body_stream::BodyStream; pub use self::body_stream::BodyStream;
pub use self::message_body::MessageBody; pub use self::message_body::MessageBody;
@ -76,10 +77,10 @@ mod tests {
use super::*; use super::*;
impl Body { impl AnyBody {
pub(crate) fn get_ref(&self) -> &[u8] { pub(crate) fn get_ref(&self) -> &[u8] {
match *self { match *self {
Body::Bytes(ref bin) => bin, AnyBody::Bytes(ref bin) => bin,
_ => panic!(), _ => panic!(),
} }
} }
@ -87,9 +88,9 @@ mod tests {
#[actix_rt::test] #[actix_rt::test]
async fn test_static_str() { async fn test_static_str() {
assert_eq!(Body::from("").size(), BodySize::Sized(0)); assert_eq!(AnyBody::from("").size(), BodySize::Sized(0));
assert_eq!(Body::from("test").size(), BodySize::Sized(4)); assert_eq!(AnyBody::from("test").size(), BodySize::Sized(4));
assert_eq!(Body::from("test").get_ref(), b"test"); assert_eq!(AnyBody::from("test").get_ref(), b"test");
assert_eq!("test".size(), BodySize::Sized(4)); assert_eq!("test".size(), BodySize::Sized(4));
assert_eq!( assert_eq!(
@ -103,13 +104,16 @@ mod tests {
#[actix_rt::test] #[actix_rt::test]
async fn test_static_bytes() { async fn test_static_bytes() {
assert_eq!(Body::from(b"test".as_ref()).size(), BodySize::Sized(4)); assert_eq!(AnyBody::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()).get_ref(), b"test");
assert_eq!( assert_eq!(
Body::copy_from_slice(b"test".as_ref()).size(), AnyBody::copy_from_slice(b"test".as_ref()).size(),
BodySize::Sized(4) 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"[..]); let sb = Bytes::from(&b"test"[..]);
pin!(sb); pin!(sb);
@ -122,8 +126,8 @@ mod tests {
#[actix_rt::test] #[actix_rt::test]
async fn test_vec() { async fn test_vec() {
assert_eq!(Body::from(Vec::from("test")).size(), BodySize::Sized(4)); assert_eq!(AnyBody::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")).get_ref(), b"test");
let test_vec = Vec::from("test"); let test_vec = Vec::from("test");
pin!(test_vec); pin!(test_vec);
@ -140,8 +144,8 @@ mod tests {
#[actix_rt::test] #[actix_rt::test]
async fn test_bytes() { async fn test_bytes() {
let b = Bytes::from("test"); let b = Bytes::from("test");
assert_eq!(Body::from(b.clone()).size(), BodySize::Sized(4)); assert_eq!(AnyBody::from(b.clone()).size(), BodySize::Sized(4));
assert_eq!(Body::from(b.clone()).get_ref(), b"test"); assert_eq!(AnyBody::from(b.clone()).get_ref(), b"test");
pin!(b); pin!(b);
assert_eq!(b.size(), BodySize::Sized(4)); assert_eq!(b.size(), BodySize::Sized(4));
@ -154,8 +158,8 @@ mod tests {
#[actix_rt::test] #[actix_rt::test]
async fn test_bytes_mut() { async fn test_bytes_mut() {
let b = BytesMut::from("test"); let b = BytesMut::from("test");
assert_eq!(Body::from(b.clone()).size(), BodySize::Sized(4)); assert_eq!(AnyBody::from(b.clone()).size(), BodySize::Sized(4));
assert_eq!(Body::from(b.clone()).get_ref(), b"test"); assert_eq!(AnyBody::from(b.clone()).get_ref(), b"test");
pin!(b); pin!(b);
assert_eq!(b.size(), BodySize::Sized(4)); assert_eq!(b.size(), BodySize::Sized(4));
@ -168,10 +172,10 @@ mod tests {
#[actix_rt::test] #[actix_rt::test]
async fn test_string() { async fn test_string() {
let b = "test".to_owned(); let b = "test".to_owned();
assert_eq!(Body::from(b.clone()).size(), BodySize::Sized(4)); assert_eq!(AnyBody::from(b.clone()).size(), BodySize::Sized(4));
assert_eq!(Body::from(b.clone()).get_ref(), b"test"); assert_eq!(AnyBody::from(b.clone()).get_ref(), b"test");
assert_eq!(Body::from(&b).size(), BodySize::Sized(4)); assert_eq!(AnyBody::from(&b).size(), BodySize::Sized(4));
assert_eq!(Body::from(&b).get_ref(), b"test"); assert_eq!(AnyBody::from(&b).get_ref(), b"test");
pin!(b); pin!(b);
assert_eq!(b.size(), BodySize::Sized(4)); assert_eq!(b.size(), BodySize::Sized(4));
@ -204,29 +208,33 @@ mod tests {
#[actix_rt::test] #[actix_rt::test]
async fn test_body_eq() { async fn test_body_eq() {
assert!( assert!(
Body::Bytes(Bytes::from_static(b"1")) AnyBody::Bytes(Bytes::from_static(b"1"))
== Body::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] #[actix_rt::test]
async fn test_body_debug() { async fn test_body_debug() {
assert!(format!("{:?}", Body::None).contains("Body::None")); assert!(format!("{:?}", AnyBody::<BoxBody>::None).contains("Body::None"));
assert!(format!("{:?}", Body::Bytes(Bytes::from_static(b"1"))).contains('1')); assert!(format!("{:?}", AnyBody::from(Bytes::from_static(b"1"))).contains('1'));
} }
#[actix_rt::test] #[actix_rt::test]
async fn test_serde_json() { async fn test_serde_json() {
use serde_json::{json, Value}; use serde_json::{json, Value};
assert_eq!( assert_eq!(
Body::from(serde_json::to_vec(&Value::String("test".to_owned())).unwrap()) AnyBody::from(
.size(), serde_json::to_vec(&Value::String("test".to_owned())).unwrap()
)
.size(),
BodySize::Sized(6) BodySize::Sized(6)
); );
assert_eq!( assert_eq!(
Body::from(serde_json::to_vec(&json!({"test-key":"test-value"})).unwrap()) AnyBody::from(
.size(), serde_json::to_vec(&json!({"test-key":"test-value"})).unwrap()
)
.size(),
BodySize::Sized(25) BodySize::Sized(25)
); );
} }
@ -250,11 +258,11 @@ mod tests {
#[actix_rt::test] #[actix_rt::test]
async fn test_to_bytes() { async fn test_to_bytes() {
let body = Body::empty(); let body = AnyBody::empty();
let bytes = to_bytes(body).await.unwrap(); let bytes = to_bytes(body).await.unwrap();
assert!(bytes.is_empty()); 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(); let bytes = to_bytes(body).await.unwrap();
assert_eq!(bytes, b"123"[..]); 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 derive_more::{Display, Error, From};
use http::{uri::InvalidUri, StatusCode}; use http::{uri::InvalidUri, StatusCode};
use crate::{ use crate::{body::AnyBody, ws, Response};
body::{AnyBody, Body},
ws, Response,
};
pub use http::Error as HttpError; 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 { pub(crate) fn new_http() -> Self {
Self::new(Kind::Http) Self::new(Kind::Http)
} }
@ -49,14 +51,12 @@ impl Error {
Self::new(Kind::SendResponse) Self::new(Kind::SendResponse)
} }
// TODO: remove allow #[allow(unused)] // reserved for future use (TODO: remove allow when being used)
#[allow(dead_code)]
pub(crate) fn new_io() -> Self { pub(crate) fn new_io() -> Self {
Self::new(Kind::Io) Self::new(Kind::Io)
} }
// used in encoder behind feature flag so ignore unused warning #[allow(unused)] // used in encoder behind feature flag so ignore unused warning
#[allow(unused)]
pub(crate) fn new_encoder() -> Self { pub(crate) fn new_encoder() -> Self {
Self::new(Kind::Encoder) Self::new(Kind::Encoder)
} }
@ -64,11 +64,6 @@ impl Error {
pub(crate) fn new_ws() -> Self { pub(crate) fn new_ws() -> Self {
Self::new(Kind::Ws) 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> { impl From<Error> for Response<AnyBody> {
@ -78,12 +73,12 @@ impl From<Error> for Response<AnyBody> {
_ => StatusCode::INTERNAL_SERVER_ERROR, _ => 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)] #[derive(Debug, Clone, Copy, PartialEq, Eq, Display)]
pub enum Kind { pub(crate) enum Kind {
#[display(fmt = "error processing HTTP")] #[display(fmt = "error processing HTTP")]
Http, Http,

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -9,7 +9,7 @@ use std::{
}; };
use actix_http::{ use actix_http::{
body::{AnyBody, Body, BodyStream}, body::{AnyBody, BodyStream},
http::{ http::{
header::{self, HeaderMap, HeaderName, IntoHeaderValue}, header::{self, HeaderMap, HeaderName, IntoHeaderValue},
Error as HttpError, Error as HttpError,
@ -196,7 +196,7 @@ impl RequestSender {
body: B, body: B,
) -> SendClientRequest ) -> SendClientRequest
where where
B: Into<Body>, B: Into<AnyBody>,
{ {
let req = match self { let req = match self {
RequestSender::Owned(head) => { RequestSender::Owned(head) => {
@ -236,7 +236,7 @@ impl RequestSender {
response_decompress, response_decompress,
timeout, timeout,
config, config,
Body::Bytes(Bytes::from(body)), AnyBody::Bytes(Bytes::from(body)),
) )
} }
@ -265,7 +265,7 @@ impl RequestSender {
response_decompress, response_decompress,
timeout, timeout,
config, config,
Body::Bytes(Bytes::from(body)), AnyBody::Bytes(Bytes::from(body)),
) )
} }
@ -297,7 +297,7 @@ impl RequestSender {
timeout: Option<Duration>, timeout: Option<Duration>,
config: &ClientConfig, config: &ClientConfig,
) -> SendClientRequest { ) -> 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> 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::marker::PhantomData;
use std::rc::Rc; use std::rc::Rc;
use actix_http::body::{Body, MessageBody}; use actix_http::body::{AnyBody, MessageBody};
use actix_http::{Extensions, Request}; use actix_http::{Extensions, Request};
use actix_service::boxed::{self, BoxServiceFactory}; use actix_service::boxed::{self, BoxServiceFactory};
use actix_service::{ use actix_service::{
@ -39,7 +39,7 @@ pub struct App<T, B> {
_phantom: PhantomData<B>, _phantom: PhantomData<B>,
} }
impl App<AppEntry, Body> { impl App<AppEntry, AnyBody> {
/// Create application builder. Application can be configured with a builder-like pattern. /// Create application builder. Application can be configured with a builder-like pattern.
#[allow(clippy::new_without_default)] #[allow(clippy::new_without_default)]
pub fn new() -> Self { 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::json::JsonBody;
pub use crate::types::readlines::Readlines; pub use crate::types::readlines::Readlines;
#[allow(deprecated)]
pub use actix_http::body::{AnyBody, Body, BodySize, MessageBody, SizedStream}; pub use actix_http::body::{AnyBody, Body, BodySize, MessageBody, SizedStream};
#[cfg(feature = "__compress")] #[cfg(feature = "__compress")]

View file

@ -1,6 +1,6 @@
use std::{cell::RefCell, fmt, io::Write as _}; 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 bytes::{BufMut as _, BytesMut};
use crate::{Error, HttpRequest, HttpResponse, Responder, ResponseError}; use crate::{Error, HttpRequest, HttpResponse, Responder, ResponseError};
@ -88,7 +88,7 @@ where
header::CONTENT_TYPE, header::CONTENT_TYPE,
header::HeaderValue::from_static("text/plain; charset=utf-8"), 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) => { InternalErrorType::Response(ref resp) => {

View file

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

View file

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

View file

@ -8,7 +8,7 @@ use std::{
}; };
use actix_http::{ use actix_http::{
body::{AnyBody, Body, MessageBody}, body::{AnyBody, MessageBody},
http::{header::HeaderMap, StatusCode}, http::{header::HeaderMap, StatusCode},
Extensions, Response, ResponseHead, 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 // Future is only implemented for AnyBody payload type because it's the most useful for making
// handlers without async blocks. Making it generic over all MessageBody types requires a future // simple handlers without async blocks. Making it generic over all MessageBody types requires a
// impl on Response which would cause it's body field to be, undesirably, Option<B>. // 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 // 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. // not be invoked if performance is important. Prefer an async fn/block in such cases.
impl Future for HttpResponse<Body> { impl Future for HttpResponse<AnyBody> {
type Output = Result<Response<Body>, Error>; type Output = Result<Response<AnyBody>, Error>;
fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> { fn poll(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Self::Output> {
if let Some(err) = self.error.take() { if let Some(err) = self.error.take() {

View file

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

View file

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

View file

@ -200,7 +200,7 @@ async fn test_body_encoding_override() {
.body(STR) .body(STR)
}))) })))
.service(web::resource("/raw").route(web::to(|| { .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 = let mut response =
HttpResponse::with_body(actix_web::http::StatusCode::OK, body); HttpResponse::with_body(actix_web::http::StatusCode::OK, body);