From 3d45a97db939dc247115f10b50126aec7ef751f4 Mon Sep 17 00:00:00 2001 From: David Pedersen Date: Sat, 7 Aug 2021 12:22:14 +0200 Subject: [PATCH] Make `FromRequest` default to use `axum::body::Body` (#146) Most users will implement `FromRequest` so making that the default makes things a bit easier to use. --- CHANGELOG.md | 2 +- src/body.rs | 1 + src/extract/mod.rs | 42 +++++++++++++++++++++++++++++++++++++++++- 3 files changed, 43 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b5bb1561..3e4d683f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,7 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 # Unreleased -None. +- Make `FromRequest` default to being generic over `axum::body::Body` ([#146](https://github.com/tokio-rs/axum/pull/146)) ## Breaking changes diff --git a/src/body.rs b/src/body.rs index 767f2daf..c18c8823 100644 --- a/src/body.rs +++ b/src/body.rs @@ -5,6 +5,7 @@ use http_body::Body as _; use std::{error::Error as StdError, fmt}; use tower::BoxError; +#[doc(no_inline)] pub use hyper::body::Body; /// A boxed [`Body`] trait object. diff --git a/src/extract/mod.rs b/src/extract/mod.rs index ae99398c..6115feb1 100644 --- a/src/extract/mod.rs +++ b/src/extract/mod.rs @@ -304,8 +304,48 @@ pub use self::typed_header::TypedHeader; /// Types that can be created from requests. /// /// See the [module docs](crate::extract) for more details. +/// +/// # What is the `B` type parameter? +/// +/// `FromRequest` is generic over the request body (the `B` in +/// [`http::Request`]). This is to allow `FromRequest` to be usable will any +/// type of request body. This is necessary because some middleware change the +/// request body, for example to add timeouts. +/// +/// If you're writing your own `FromRequest` that wont be used outside your +/// application, and not using any middleware that changes the request body, you +/// can most likely use `axum::body::Body`. Note this is also the default. +/// +/// If you're writing a library, thats intended for others to use, its recommended +/// to keep the generic type parameter: +/// +/// ```rust +/// use axum::{ +/// async_trait, +/// extract::{FromRequest, RequestParts}, +/// }; +/// +/// struct MyExtractor; +/// +/// #[async_trait] +/// impl FromRequest for MyExtractor +/// where +/// B: Send, // required by `async_trait` +/// { +/// type Rejection = http::StatusCode; +/// +/// async fn from_request(req: &mut RequestParts) -> Result { +/// // ... +/// # unimplemented!() +/// } +/// } +/// ``` +/// +/// This ensures your extractor is as flexible as possible. +/// +/// [`http::Request`]: http::Request #[async_trait] -pub trait FromRequest: Sized { +pub trait FromRequest: Sized { /// If the extractor fails it'll use this "rejection" type. A rejection is /// a kind of error that can be converted into a response. type Rejection: IntoResponse;