Files
axum/src/body.rs
T

47 lines
1.2 KiB
Rust
Raw Normal View History

2021-06-07 15:45:19 +02:00
//! HTTP body utilities.
use bytes::Bytes;
2021-07-22 13:23:50 +02:00
use http_body::Body as _;
use std::{error::Error as StdError, fmt};
use tower::BoxError;
2021-05-30 04:28:24 +02:00
2021-05-30 13:24:03 +02:00
pub use hyper::body::Body;
2021-05-30 04:28:24 +02:00
/// A boxed [`Body`] trait object.
2021-06-08 21:21:20 +02:00
///
/// This is used in axum as the response body type for applications. Its
/// necessary to unify multiple response bodies types into one.
2021-07-22 13:23:50 +02:00
pub type BoxBody = http_body::combinators::BoxBody<Bytes, BoxStdError>;
2021-05-30 04:28:24 +02:00
/// Convert a [`http_body::Body`] into a [`BoxBody`].
pub fn box_body<B>(body: B) -> BoxBody
where
2021-07-22 13:23:50 +02:00
B: http_body::Body<Data = Bytes> + Send + Sync + 'static,
B::Error: Into<BoxError>,
{
2021-07-22 13:23:50 +02:00
body.map_err(|err| BoxStdError(err.into())).boxed()
}
pub(crate) fn empty() -> BoxBody {
box_body(http_body::Empty::new())
2021-06-01 00:34:09 +02:00
}
2021-06-06 11:37:08 +02:00
2021-06-06 23:58:44 +02:00
/// A boxed error trait object that implements [`std::error::Error`].
///
/// This is necessary for compatibility with middleware that changes the error
/// type of the response body.
2021-06-08 22:27:38 +02:00
#[derive(Debug)]
pub struct BoxStdError(pub(crate) tower::BoxError);
impl StdError for BoxStdError {
fn source(&self) -> std::option::Option<&(dyn StdError + 'static)> {
self.0.source()
}
}
impl fmt::Display for BoxStdError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self.0.fmt(f)
}
}