Make extractors easier to write (#36)

Previously extractors worked directly on `Request<B>` which meant you
had to do weird tricks like `mem::take(req.headers_mut())` to get owned
parts of the request.

This changes that instead to use a new `RequestParts` type that have
methods to "take" each part of the request. Without having to do weird
tricks.

Also removed the need to have `B: Default` for body extractors.
This commit is contained in:
David Pedersen
2021-07-22 13:23:50 +02:00
committed by GitHub
parent e544fe1c39
commit f32d325e55
12 changed files with 441 additions and 193 deletions
+11 -73
View File
@@ -1,13 +1,8 @@
//! HTTP body utilities.
use bytes::Bytes;
use http_body::{Empty, Full};
use std::{
error::Error as StdError,
fmt,
pin::Pin,
task::{Context, Poll},
};
use http_body::Body as _;
use std::{error::Error as StdError, fmt};
use tower::BoxError;
pub use hyper::body::Body;
@@ -16,75 +11,18 @@ pub use hyper::body::Body;
///
/// This is used in axum as the response body type for applications. Its necessary to unify
/// multiple response bodies types into one.
pub struct BoxBody {
// when we've gotten rid of `BoxStdError` we should be able to change the error type to
// `BoxError`
inner: Pin<Box<dyn http_body::Body<Data = Bytes, Error = BoxStdError> + Send + Sync + 'static>>,
}
pub type BoxBody = http_body::combinators::BoxBody<Bytes, BoxStdError>;
impl BoxBody {
/// Create a new `BoxBody`.
pub fn new<B>(body: B) -> Self
where
B: http_body::Body<Data = Bytes> + Send + Sync + 'static,
B::Error: Into<BoxError>,
{
Self {
inner: Box::pin(body.map_err(|error| BoxStdError(error.into()))),
}
}
pub(crate) fn empty() -> Self {
Self::new(Empty::new())
}
}
impl Default for BoxBody {
fn default() -> Self {
BoxBody::empty()
}
}
impl fmt::Debug for BoxBody {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BoxBody").finish()
}
}
impl http_body::Body for BoxBody {
type Data = Bytes;
type Error = BoxStdError;
fn poll_data(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<Self::Data, Self::Error>>> {
self.inner.as_mut().poll_data(cx)
}
fn poll_trailers(
mut self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Result<Option<http::HeaderMap>, Self::Error>> {
self.inner.as_mut().poll_trailers(cx)
}
fn is_end_stream(&self) -> bool {
self.inner.is_end_stream()
}
fn size_hint(&self) -> http_body::SizeHint {
self.inner.size_hint()
}
}
impl<B> From<B> for BoxBody
pub(crate) fn box_body<B>(body: B) -> BoxBody
where
B: Into<Bytes>,
B: http_body::Body<Data = Bytes> + Send + Sync + 'static,
B::Error: Into<BoxError>,
{
fn from(s: B) -> Self {
BoxBody::new(Full::from(s.into()))
}
body.map_err(|err| BoxStdError(err.into())).boxed()
}
pub(crate) fn empty() -> BoxBody {
box_body(http_body::Empty::new())
}
/// A boxed error trait object that implements [`std::error::Error`].