diff --git a/axum-core/Cargo.toml b/axum-core/Cargo.toml index 4373dadcfe..11d8635479 100644 --- a/axum-core/Cargo.toml +++ b/axum-core/Cargo.toml @@ -24,6 +24,8 @@ futures-util = { version = "0.3", default-features = false, features = ["alloc"] http = "0.2.7" http-body = "0.4.5" mime = "0.3.16" +pin-project-lite = "0.2.7" +sync_wrapper = "0.1.1" tower-layer = "0.3" tower-service = "0.3" @@ -35,7 +37,8 @@ tracing = { version = "0.1.37", default-features = false, optional = true } rustversion = "1.0.9" [dev-dependencies] -axum = { path = "../axum", version = "0.6.0", features = ["headers"] } +axum = { path = "../axum", version = "0.6.0" } +axum-extra = { path = "../axum-extra", features = ["typed-header"] } futures-util = { version = "0.3", default-features = false, features = ["alloc"] } hyper = "0.14.24" tokio = { version = "1.25.0", features = ["macros"] } diff --git a/axum-core/src/body.rs b/axum-core/src/body.rs index 9f25408936..89e69218bd 100644 --- a/axum-core/src/body.rs +++ b/axum-core/src/body.rs @@ -3,16 +3,18 @@ use crate::{BoxError, Error}; use bytes::Bytes; use bytes::{Buf, BufMut}; -use http_body::Body; +use futures_util::stream::Stream; +use futures_util::TryStream; +use http::HeaderMap; +use http_body::Body as _; +use pin_project_lite::pin_project; +use std::pin::Pin; +use std::task::{Context, Poll}; +use sync_wrapper::SyncWrapper; -/// A boxed [`Body`] trait object. -/// -/// This is used in axum as the response body type for applications. It's -/// necessary to unify multiple response bodies types into one. -pub type BoxBody = http_body::combinators::UnsyncBoxBody; +type BoxBody = http_body::combinators::UnsyncBoxBody; -/// Convert a [`http_body::Body`] into a [`BoxBody`]. -pub fn boxed(body: B) -> BoxBody +fn boxed(body: B) -> BoxBody where B: http_body::Body + Send + 'static, B::Error: Into, @@ -55,7 +57,7 @@ where // THE SOFTWARE. pub(crate) async fn to_bytes(body: T) -> Result where - T: Body, + T: http_body::Body, { futures_util::pin_mut!(body); @@ -85,6 +87,143 @@ where Ok(vec.into()) } +/// The body type used in axum requests and responses. +#[derive(Debug)] +pub struct Body(BoxBody); + +impl Body { + /// Create a new `Body` that wraps another [`http_body::Body`]. + pub fn new(body: B) -> Self + where + B: http_body::Body + Send + 'static, + B::Error: Into, + { + try_downcast(body).unwrap_or_else(|body| Self(boxed(body))) + } + + /// Create an empty body. + pub fn empty() -> Self { + Self::new(http_body::Empty::new()) + } + + /// Create a new `Body` from a [`Stream`]. + /// + /// [`Stream`]: futures_util::stream::Stream + pub fn from_stream(stream: S) -> Self + where + S: TryStream + Send + 'static, + S::Ok: Into, + S::Error: Into, + { + Self::new(StreamBody { + stream: SyncWrapper::new(stream), + }) + } +} + +impl Default for Body { + fn default() -> Self { + Self::empty() + } +} + +macro_rules! body_from_impl { + ($ty:ty) => { + impl From<$ty> for Body { + fn from(buf: $ty) -> Self { + Self::new(http_body::Full::from(buf)) + } + } + }; +} + +body_from_impl!(&'static [u8]); +body_from_impl!(std::borrow::Cow<'static, [u8]>); +body_from_impl!(Vec); + +body_from_impl!(&'static str); +body_from_impl!(std::borrow::Cow<'static, str>); +body_from_impl!(String); + +body_from_impl!(Bytes); + +impl http_body::Body for Body { + type Data = Bytes; + type Error = Error; + + #[inline] + fn poll_data( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> std::task::Poll>> { + Pin::new(&mut self.0).poll_data(cx) + } + + #[inline] + fn poll_trailers( + mut self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> std::task::Poll, Self::Error>> { + Pin::new(&mut self.0).poll_trailers(cx) + } + + #[inline] + fn size_hint(&self) -> http_body::SizeHint { + self.0.size_hint() + } + + #[inline] + fn is_end_stream(&self) -> bool { + self.0.is_end_stream() + } +} + +impl Stream for Body { + type Item = Result; + + #[inline] + fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + self.poll_data(cx) + } +} + +pin_project! { + struct StreamBody { + #[pin] + stream: SyncWrapper, + } +} + +impl http_body::Body for StreamBody +where + S: TryStream, + S::Ok: Into, + S::Error: Into, +{ + type Data = Bytes; + type Error = Error; + + fn poll_data( + self: Pin<&mut Self>, + cx: &mut Context<'_>, + ) -> Poll>> { + let stream = self.project().stream.get_pin_mut(); + match futures_util::ready!(stream.try_poll_next(cx)) { + Some(Ok(chunk)) => Poll::Ready(Some(Ok(chunk.into()))), + Some(Err(err)) => Poll::Ready(Some(Err(Error::new(err)))), + None => Poll::Ready(None), + } + } + + #[inline] + fn poll_trailers( + self: Pin<&mut Self>, + _cx: &mut Context<'_>, + ) -> Poll, Self::Error>> { + Poll::Ready(Ok(None)) + } +} + #[test] fn test_try_downcast() { assert_eq!(try_downcast::(5_u32), Err(5_u32)); diff --git a/axum-core/src/ext_traits/request.rs b/axum-core/src/ext_traits/request.rs index e49ba9216c..a891922e47 100644 --- a/axum-core/src/ext_traits/request.rs +++ b/axum-core/src/ext_traits/request.rs @@ -1,15 +1,15 @@ -use crate::extract::{DefaultBodyLimitKind, FromRequest, FromRequestParts}; +use crate::body::Body; +use crate::extract::{DefaultBodyLimitKind, FromRequest, FromRequestParts, Request}; use futures_util::future::BoxFuture; -use http::Request; use http_body::Limited; mod sealed { - pub trait Sealed {} - impl Sealed for http::Request {} + pub trait Sealed {} + impl Sealed for http::Request {} } /// Extension trait that adds additional methods to [`Request`]. -pub trait RequestExt: sealed::Sealed + Sized { +pub trait RequestExt: sealed::Sealed + Sized { /// Apply an extractor to this `Request`. /// /// This is just a convenience for `E::from_request(req, &())`. @@ -22,8 +22,9 @@ pub trait RequestExt: sealed::Sealed + Sized { /// ``` /// use axum::{ /// async_trait, - /// extract::FromRequest, - /// http::{header::CONTENT_TYPE, Request, StatusCode}, + /// extract::{Request, FromRequest}, + /// body::Body, + /// http::{header::CONTENT_TYPE, StatusCode}, /// response::{IntoResponse, Response}, /// Form, Json, RequestExt, /// }; @@ -31,17 +32,16 @@ pub trait RequestExt: sealed::Sealed + Sized { /// struct FormOrJson(T); /// /// #[async_trait] - /// impl FromRequest for FormOrJson + /// impl FromRequest for FormOrJson /// where - /// Json: FromRequest<(), B>, - /// Form: FromRequest<(), B>, + /// Json: FromRequest<()>, + /// Form: FromRequest<()>, /// T: 'static, - /// B: Send + 'static, /// S: Send + Sync, /// { /// type Rejection = Response; /// - /// async fn from_request(req: Request, _state: &S) -> Result { + /// async fn from_request(req: Request, _state: &S) -> Result { /// let content_type = req /// .headers() /// .get(CONTENT_TYPE) @@ -70,7 +70,7 @@ pub trait RequestExt: sealed::Sealed + Sized { /// ``` fn extract(self) -> BoxFuture<'static, Result> where - E: FromRequest<(), B, M> + 'static, + E: FromRequest<(), M> + 'static, M: 'static; /// Apply an extractor that requires some state to this `Request`. @@ -85,8 +85,8 @@ pub trait RequestExt: sealed::Sealed + Sized { /// ``` /// use axum::{ /// async_trait, - /// extract::{FromRef, FromRequest}, - /// http::Request, + /// body::Body, + /// extract::{Request, FromRef, FromRequest}, /// RequestExt, /// }; /// @@ -95,15 +95,14 @@ pub trait RequestExt: sealed::Sealed + Sized { /// } /// /// #[async_trait] - /// impl FromRequest for MyExtractor + /// impl FromRequest for MyExtractor /// where /// String: FromRef, /// S: Send + Sync, - /// B: Send + 'static, /// { /// type Rejection = std::convert::Infallible; /// - /// async fn from_request(req: Request, state: &S) -> Result { + /// async fn from_request(req: Request, state: &S) -> Result { /// let requires_state = req.extract_with_state::(state).await?; /// /// Ok(Self { requires_state }) @@ -114,22 +113,21 @@ pub trait RequestExt: sealed::Sealed + Sized { /// struct RequiresState { /* ... */ } /// /// #[async_trait] - /// impl FromRequest for RequiresState + /// impl FromRequest for RequiresState /// where /// String: FromRef, /// S: Send + Sync, - /// B: Send + 'static, /// { /// // ... /// # type Rejection = std::convert::Infallible; - /// # async fn from_request(req: Request, _state: &S) -> Result { + /// # async fn from_request(req: Request, _state: &S) -> Result { /// # todo!() /// # } /// } /// ``` fn extract_with_state(self, state: &S) -> BoxFuture<'_, Result> where - E: FromRequest + 'static, + E: FromRequest + 'static, S: Send + Sync; /// Apply a parts extractor to this `Request`. @@ -141,32 +139,36 @@ pub trait RequestExt: sealed::Sealed + Sized { /// ``` /// use axum::{ /// async_trait, - /// extract::FromRequest, - /// headers::{authorization::Bearer, Authorization}, - /// http::Request, + /// extract::{Path, Request, FromRequest}, /// response::{IntoResponse, Response}, - /// Json, RequestExt, TypedHeader, + /// body::Body, + /// Json, RequestExt, + /// }; + /// use axum_extra::{ + /// TypedHeader, + /// headers::{authorization::Bearer, Authorization}, /// }; + /// use std::collections::HashMap; /// /// struct MyExtractor { - /// bearer_token: String, + /// path_params: HashMap, /// payload: T, /// } /// /// #[async_trait] - /// impl FromRequest for MyExtractor + /// impl FromRequest for MyExtractor /// where - /// B: Send + 'static, /// S: Send + Sync, - /// Json: FromRequest<(), B>, + /// Json: FromRequest<()>, /// T: 'static, /// { /// type Rejection = Response; /// - /// async fn from_request(mut req: Request, _state: &S) -> Result { - /// let TypedHeader(auth_header) = req - /// .extract_parts::>>() + /// async fn from_request(mut req: Request, _state: &S) -> Result { + /// let path_params = req + /// .extract_parts::>() /// .await + /// .map(|Path(path_params)| path_params) /// .map_err(|err| err.into_response())?; /// /// let Json(payload) = req @@ -174,10 +176,7 @@ pub trait RequestExt: sealed::Sealed + Sized { /// .await /// .map_err(|err| err.into_response())?; /// - /// Ok(Self { - /// bearer_token: auth_header.token().to_owned(), - /// payload, - /// }) + /// Ok(Self { path_params, payload }) /// } /// } /// ``` @@ -194,9 +193,10 @@ pub trait RequestExt: sealed::Sealed + Sized { /// ``` /// use axum::{ /// async_trait, - /// extract::{FromRef, FromRequest, FromRequestParts}, - /// http::{request::Parts, Request}, + /// extract::{Request, FromRef, FromRequest, FromRequestParts}, + /// http::request::Parts, /// response::{IntoResponse, Response}, + /// body::Body, /// Json, RequestExt, /// }; /// @@ -206,17 +206,16 @@ pub trait RequestExt: sealed::Sealed + Sized { /// } /// /// #[async_trait] - /// impl FromRequest for MyExtractor + /// impl FromRequest for MyExtractor /// where /// String: FromRef, - /// Json: FromRequest<(), B>, + /// Json: FromRequest<()>, /// T: 'static, /// S: Send + Sync, - /// B: Send + 'static, /// { /// type Rejection = Response; /// - /// async fn from_request(mut req: Request, state: &S) -> Result { + /// async fn from_request(mut req: Request, state: &S) -> Result { /// let requires_state = req /// .extract_parts_with_state::(state) /// .await @@ -260,21 +259,18 @@ pub trait RequestExt: sealed::Sealed + Sized { /// Apply the [default body limit](crate::extract::DefaultBodyLimit). /// /// If it is disabled, return the request as-is in `Err`. - fn with_limited_body(self) -> Result>, Request>; + fn with_limited_body(self) -> Result>, Request>; /// Consumes the request, returning the body wrapped in [`Limited`] if a /// [default limit](crate::extract::DefaultBodyLimit) is in place, or not wrapped if the /// default limit is disabled. - fn into_limited_body(self) -> Result, B>; + fn into_limited_body(self) -> Result, Body>; } -impl RequestExt for Request -where - B: Send + 'static, -{ +impl RequestExt for Request { fn extract(self) -> BoxFuture<'static, Result> where - E: FromRequest<(), B, M> + 'static, + E: FromRequest<(), M> + 'static, M: 'static, { self.extract_with_state(&()) @@ -282,7 +278,7 @@ where fn extract_with_state(self, state: &S) -> BoxFuture<'_, Result> where - E: FromRequest + 'static, + E: FromRequest + 'static, S: Send + Sync, { E::from_request(self, state) @@ -324,7 +320,7 @@ where }) } - fn with_limited_body(self) -> Result>, Request> { + fn with_limited_body(self) -> Result>, Request> { // update docs in `axum-core/src/extract/default_body_limit.rs` and // `axum/src/docs/extract.md` if this changes const DEFAULT_LIMIT: usize = 2_097_152; // 2 mb @@ -338,7 +334,7 @@ where } } - fn into_limited_body(self) -> Result, B> { + fn into_limited_body(self) -> Result, Body> { self.with_limited_body() .map(Request::into_body) .map_err(Request::into_body) @@ -354,11 +350,10 @@ mod tests { }; use async_trait::async_trait; use http::Method; - use hyper::Body; #[tokio::test] async fn extract_without_state() { - let req = Request::new(()); + let req = Request::new(Body::empty()); let method: Method = req.extract().await.unwrap(); @@ -376,7 +371,7 @@ mod tests { #[tokio::test] async fn extract_with_state() { - let req = Request::new(()); + let req = Request::new(Body::empty()); let state = "state".to_owned(); @@ -387,7 +382,10 @@ mod tests { #[tokio::test] async fn extract_parts_without_state() { - let mut req = Request::builder().header("x-foo", "foo").body(()).unwrap(); + let mut req = Request::builder() + .header("x-foo", "foo") + .body(Body::empty()) + .unwrap(); let method: Method = req.extract_parts().await.unwrap(); @@ -397,7 +395,10 @@ mod tests { #[tokio::test] async fn extract_parts_with_state() { - let mut req = Request::builder().header("x-foo", "foo").body(()).unwrap(); + let mut req = Request::builder() + .header("x-foo", "foo") + .body(Body::empty()) + .unwrap(); let state = "state".to_owned(); @@ -417,15 +418,14 @@ mod tests { } #[async_trait] - impl FromRequest for WorksForCustomExtractor + impl FromRequest for WorksForCustomExtractor where S: Send + Sync, - B: Send + 'static, - String: FromRef + FromRequest<(), B>, + String: FromRef + FromRequest<()>, { - type Rejection = >::Rejection; + type Rejection = >::Rejection; - async fn from_request(mut req: Request, state: &S) -> Result { + async fn from_request(mut req: Request, state: &S) -> Result { let RequiresState(from_state) = req.extract_parts_with_state(state).await.unwrap(); let method = req.extract_parts().await.unwrap(); let body = req.extract().await?; diff --git a/axum-core/src/ext_traits/request_parts.rs b/axum-core/src/ext_traits/request_parts.rs index 07a7dbff30..e7063f4d8b 100644 --- a/axum-core/src/ext_traits/request_parts.rs +++ b/axum-core/src/ext_traits/request_parts.rs @@ -17,9 +17,8 @@ pub trait RequestPartsExt: sealed::Sealed + Sized { /// /// ``` /// use axum::{ - /// extract::{Query, TypedHeader, FromRequestParts}, + /// extract::{Query, Path, FromRequestParts}, /// response::{Response, IntoResponse}, - /// headers::UserAgent, /// http::request::Parts, /// RequestPartsExt, /// async_trait, @@ -27,7 +26,7 @@ pub trait RequestPartsExt: sealed::Sealed + Sized { /// use std::collections::HashMap; /// /// struct MyExtractor { - /// user_agent: String, + /// path_params: HashMap, /// query_params: HashMap, /// } /// @@ -39,10 +38,10 @@ pub trait RequestPartsExt: sealed::Sealed + Sized { /// type Rejection = Response; /// /// async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { - /// let user_agent = parts - /// .extract::>() + /// let path_params = parts + /// .extract::>>() /// .await - /// .map(|user_agent| user_agent.as_str().to_owned()) + /// .map(|Path(path_params)| path_params) /// .map_err(|err| err.into_response())?; /// /// let query_params = parts @@ -51,7 +50,7 @@ pub trait RequestPartsExt: sealed::Sealed + Sized { /// .map(|Query(params)| params) /// .map_err(|err| err.into_response())?; /// - /// Ok(MyExtractor { user_agent, query_params }) + /// Ok(MyExtractor { path_params, query_params }) /// } /// } /// ``` diff --git a/axum-core/src/extract/default_body_limit.rs b/axum-core/src/extract/default_body_limit.rs index 7b37f1edab..5a2cd971b5 100644 --- a/axum-core/src/extract/default_body_limit.rs +++ b/axum-core/src/extract/default_body_limit.rs @@ -30,22 +30,21 @@ use tower_layer::Layer; /// Router, /// routing::post, /// body::Body, -/// extract::{DefaultBodyLimit, RawBody}, -/// http::Request, +/// extract::{Request, DefaultBodyLimit}, /// }; /// /// let app = Router::new() /// .route( /// "/", /// // even with `DefaultBodyLimit` the request body is still just `Body` -/// post(|request: Request| async {}), +/// post(|request: Request| async {}), /// ) /// .layer(DefaultBodyLimit::max(1024)); -/// # let _: Router<(), _> = app; +/// # let _: Router = app; /// ``` /// /// ``` -/// use axum::{Router, routing::post, body::Body, extract::RawBody, http::Request}; +/// use axum::{Router, routing::post, body::Body, extract::Request}; /// use tower_http::limit::RequestBodyLimitLayer; /// use http_body::Limited; /// @@ -54,10 +53,10 @@ use tower_layer::Layer; /// "/", /// // `RequestBodyLimitLayer` changes the request body type to `Limited` /// // extracting a different body type wont work -/// post(|request: Request>| async {}), +/// post(|request: Request| async {}), /// ) /// .layer(RequestBodyLimitLayer::new(1024)); -/// # let _: Router<(), _> = app; +/// # let _: Router = app; /// ``` /// /// In general using `DefaultBodyLimit` is recommended but if you need to use third party @@ -105,7 +104,7 @@ impl DefaultBodyLimit { /// use tower_http::limit::RequestBodyLimitLayer; /// use http_body::Limited; /// - /// let app: Router<(), Limited> = Router::new() + /// let app: Router<()> = Router::new() /// .route("/", get(|body: Bytes| async {})) /// // Disable the default limit /// .layer(DefaultBodyLimit::disable()) @@ -140,7 +139,7 @@ impl DefaultBodyLimit { /// use tower_http::limit::RequestBodyLimitLayer; /// use http_body::Limited; /// - /// let app: Router<(), Limited> = Router::new() + /// let app: Router<()> = Router::new() /// .route("/", get(|body: Bytes| async {})) /// // Replace the default of 2MB with 1024 bytes. /// .layer(DefaultBodyLimit::max(1024)); diff --git a/axum-core/src/extract/mod.rs b/axum-core/src/extract/mod.rs index 1113a1ee7a..758e5a5203 100644 --- a/axum-core/src/extract/mod.rs +++ b/axum-core/src/extract/mod.rs @@ -4,9 +4,9 @@ //! //! [`axum::extract`]: https://docs.rs/axum/latest/axum/extract/index.html -use crate::response::IntoResponse; +use crate::{body::Body, response::IntoResponse}; use async_trait::async_trait; -use http::{request::Parts, Request}; +use http::request::Parts; use std::convert::Infallible; pub mod rejection; @@ -19,6 +19,10 @@ mod tuple; pub(crate) use self::default_body_limit::DefaultBodyLimitKind; pub use self::{default_body_limit::DefaultBodyLimit, from_ref::FromRef}; +/// Type alias for [`http::Request`] whose body type defaults to [`Body`], the most common body +/// type used with axum. +pub type Request = http::Request; + mod private { #[derive(Debug, Clone, Copy)] pub enum ViaParts {} @@ -64,48 +68,6 @@ pub trait FromRequestParts: Sized { /// /// See [`axum::extract`] for more general docs about extractors. /// -/// # 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 with 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`. -/// -/// If you're writing a library that's intended for others to use, it's recommended -/// to keep the generic type parameter: -/// -/// ```rust -/// use axum::{ -/// async_trait, -/// extract::FromRequest, -/// http::{self, Request}, -/// }; -/// -/// struct MyExtractor; -/// -/// #[async_trait] -/// impl FromRequest for MyExtractor -/// where -/// // these bounds are required by `async_trait` -/// B: Send + 'static, -/// S: Send + Sync, -/// { -/// type Rejection = http::StatusCode; -/// -/// async fn from_request(req: Request, state: &S) -> Result { -/// // ... -/// # unimplemented!() -/// } -/// } -/// ``` -/// -/// This ensures your extractor is as flexible as possible. -/// -/// [`http::Request`]: http::Request /// [`axum::extract`]: https://docs.rs/axum/0.6.0/axum/extract/index.html #[async_trait] #[cfg_attr( @@ -114,25 +76,24 @@ pub trait FromRequestParts: Sized { note = "Function argument is not a valid axum extractor. \nSee `https://docs.rs/axum/latest/axum/extract/index.html` for details", ) )] -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; /// Perform the extraction. - async fn from_request(req: Request, state: &S) -> Result; + async fn from_request(req: Request, state: &S) -> Result; } #[async_trait] -impl FromRequest for T +impl FromRequest for T where - B: Send + 'static, S: Send + Sync, T: FromRequestParts, { type Rejection = >::Rejection; - async fn from_request(req: Request, state: &S) -> Result { + async fn from_request(req: Request, state: &S) -> Result { let (mut parts, _) = req.into_parts(); Self::from_request_parts(&mut parts, state).await } @@ -155,15 +116,14 @@ where } #[async_trait] -impl FromRequest for Option +impl FromRequest for Option where - T: FromRequest, - B: Send + 'static, + T: FromRequest, S: Send + Sync, { type Rejection = Infallible; - async fn from_request(req: Request, state: &S) -> Result, Self::Rejection> { + async fn from_request(req: Request, state: &S) -> Result, Self::Rejection> { Ok(T::from_request(req, state).await.ok()) } } @@ -182,15 +142,14 @@ where } #[async_trait] -impl FromRequest for Result +impl FromRequest for Result where - T: FromRequest, - B: Send + 'static, + T: FromRequest, S: Send + Sync, { type Rejection = Infallible; - async fn from_request(req: Request, state: &S) -> Result { + async fn from_request(req: Request, state: &S) -> Result { Ok(T::from_request(req, state).await) } } diff --git a/axum-core/src/extract/rejection.rs b/axum-core/src/extract/rejection.rs index 958f3b2170..8b338dbc53 100644 --- a/axum-core/src/extract/rejection.rs +++ b/axum-core/src/extract/rejection.rs @@ -3,7 +3,7 @@ use crate::__composite_rejection as composite_rejection; use crate::__define_rejection as define_rejection; -use crate::BoxError; +use crate::{BoxError, Error}; composite_rejection! { /// Rejection type for extractors that buffer the request body. Used if the @@ -19,7 +19,11 @@ impl FailedToBufferBody { where E: Into, { - match err.into().downcast::() { + let box_error = match err.into().downcast::() { + Ok(err) => err.into_inner(), + Err(err) => err, + }; + match box_error.downcast::() { Ok(err) => Self::LengthLimitError(LengthLimitError::from_err(err)), Err(err) => Self::UnknownBodyError(UnknownBodyError::from_err(err)), } diff --git a/axum-core/src/extract/request_parts.rs b/axum-core/src/extract/request_parts.rs index 05d7d7277b..98943bea35 100644 --- a/axum-core/src/extract/request_parts.rs +++ b/axum-core/src/extract/request_parts.rs @@ -1,19 +1,18 @@ -use super::{rejection::*, FromRequest, FromRequestParts}; -use crate::{BoxError, RequestExt}; +use super::{rejection::*, FromRequest, FromRequestParts, Request}; +use crate::{body::Body, RequestExt}; use async_trait::async_trait; use bytes::Bytes; -use http::{request::Parts, HeaderMap, Method, Request, Uri, Version}; +use http::{request::Parts, HeaderMap, Method, Uri, Version}; use std::convert::Infallible; #[async_trait] -impl FromRequest for Request +impl FromRequest for Request where - B: Send, S: Send + Sync, { type Rejection = Infallible; - async fn from_request(req: Request, _: &S) -> Result { + async fn from_request(req: Request, _: &S) -> Result { Ok(req) } } @@ -72,16 +71,13 @@ where } #[async_trait] -impl FromRequest for Bytes +impl FromRequest for Bytes where - B: http_body::Body + Send + 'static, - B::Data: Send, - B::Error: Into, S: Send + Sync, { type Rejection = BytesRejection; - async fn from_request(req: Request, _: &S) -> Result { + async fn from_request(req: Request, _: &S) -> Result { let bytes = match req.into_limited_body() { Ok(limited_body) => crate::body::to_bytes(limited_body) .await @@ -96,16 +92,13 @@ where } #[async_trait] -impl FromRequest for String +impl FromRequest for String where - B: http_body::Body + Send + 'static, - B::Data: Send, - B::Error: Into, S: Send + Sync, { type Rejection = StringRejection; - async fn from_request(req: Request, state: &S) -> Result { + async fn from_request(req: Request, state: &S) -> Result { let bytes = Bytes::from_request(req, state) .await .map_err(|err| match err { @@ -123,14 +116,25 @@ where } #[async_trait] -impl FromRequest for Parts +impl FromRequest for Parts where - B: Send + 'static, S: Send + Sync, { type Rejection = Infallible; - async fn from_request(req: Request, _: &S) -> Result { + async fn from_request(req: Request, _: &S) -> Result { Ok(req.into_parts().0) } } + +#[async_trait] +impl FromRequest for Body +where + S: Send + Sync, +{ + type Rejection = Infallible; + + async fn from_request(req: Request, _: &S) -> Result { + Ok(req.into_body()) + } +} diff --git a/axum-core/src/extract/tuple.rs b/axum-core/src/extract/tuple.rs index 728135b2a0..021b9616df 100644 --- a/axum-core/src/extract/tuple.rs +++ b/axum-core/src/extract/tuple.rs @@ -1,7 +1,7 @@ -use super::{FromRequest, FromRequestParts}; +use super::{FromRequest, FromRequestParts, Request}; use crate::response::{IntoResponse, Response}; use async_trait::async_trait; -use http::request::{Parts, Request}; +use http::request::Parts; use std::convert::Infallible; #[async_trait] @@ -45,19 +45,18 @@ macro_rules! impl_from_request { } // This impl must not be generic over M, otherwise it would conflict with the blanket - // implementation of `FromRequest` for `T: FromRequestParts`. + // implementation of `FromRequest` for `T: FromRequestParts`. #[async_trait] #[allow(non_snake_case, unused_mut, unused_variables)] - impl FromRequest for ($($ty,)* $last,) + impl FromRequest for ($($ty,)* $last,) where $( $ty: FromRequestParts + Send, )* - $last: FromRequest + Send, - B: Send + 'static, + $last: FromRequest + Send, S: Send + Sync, { type Rejection = Response; - async fn from_request(req: Request, state: &S) -> Result { + async fn from_request(req: Request, state: &S) -> Result { let (mut parts, body) = req.into_parts(); $( @@ -85,7 +84,7 @@ mod tests { fn assert_from_request() where - T: FromRequest<(), http_body::Full, M>, + T: FromRequest<(), M>, { } diff --git a/axum-core/src/response/into_response.rs b/axum-core/src/response/into_response.rs index f19974cfb7..ab684e2c36 100644 --- a/axum-core/src/response/into_response.rs +++ b/axum-core/src/response/into_response.rs @@ -1,14 +1,11 @@ use super::{IntoResponseParts, Response, ResponseParts}; -use crate::{body, BoxError}; +use crate::{body::Body, BoxError}; use bytes::{buf::Chain, Buf, Bytes, BytesMut}; use http::{ header::{self, HeaderMap, HeaderName, HeaderValue}, Extensions, StatusCode, }; -use http_body::{ - combinators::{MapData, MapErr}, - Empty, Full, SizeHint, -}; +use http_body::SizeHint; use std::{ borrow::Cow, convert::Infallible, @@ -74,9 +71,9 @@ use std::{ /// body, /// routing::get, /// response::{IntoResponse, Response}, +/// body::Body, /// Router, /// }; -/// use http_body::Body; /// use http::HeaderMap; /// use bytes::Bytes; /// use std::{ @@ -89,7 +86,7 @@ use std::{ /// /// // First implement `Body` for `MyBody`. This could for example use /// // some custom streaming protocol. -/// impl Body for MyBody { +/// impl http_body::Body for MyBody { /// type Data = Bytes; /// type Error = Infallible; /// @@ -113,15 +110,13 @@ use std::{ /// // Now we can implement `IntoResponse` directly for `MyBody` /// impl IntoResponse for MyBody { /// fn into_response(self) -> Response { -/// Response::new(body::boxed(self)) +/// Response::new(Body::new(self)) /// } /// } /// /// // `MyBody` can now be returned from handlers. /// let app = Router::new().route("/", get(|| async { MyBody })); -/// # async { -/// # hyper::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` pub trait IntoResponse { /// Create a response. @@ -138,7 +133,7 @@ impl IntoResponse for StatusCode { impl IntoResponse for () { fn into_response(self) -> Response { - Empty::new().into_response() + Body::empty().into_response() } } @@ -167,65 +162,19 @@ where B::Error: Into, { fn into_response(self) -> Response { - self.map(body::boxed) + self.map(Body::new) } } impl IntoResponse for http::response::Parts { fn into_response(self) -> Response { - Response::from_parts(self, body::boxed(Empty::new())) - } -} - -impl IntoResponse for Full { - fn into_response(self) -> Response { - Response::new(body::boxed(self)) - } -} - -impl IntoResponse for Empty { - fn into_response(self) -> Response { - Response::new(body::boxed(self)) - } -} - -impl IntoResponse for http_body::combinators::BoxBody -where - E: Into + 'static, -{ - fn into_response(self) -> Response { - Response::new(body::boxed(self)) + Response::from_parts(self, Body::empty()) } } -impl IntoResponse for http_body::combinators::UnsyncBoxBody -where - E: Into + 'static, -{ - fn into_response(self) -> Response { - Response::new(body::boxed(self)) - } -} - -impl IntoResponse for MapData -where - B: http_body::Body + Send + 'static, - F: FnMut(B::Data) -> Bytes + Send + 'static, - B::Error: Into, -{ - fn into_response(self) -> Response { - Response::new(body::boxed(self)) - } -} - -impl IntoResponse for MapErr -where - B: http_body::Body + Send + 'static, - F: FnMut(B::Error) -> E + Send + 'static, - E: Into, -{ +impl IntoResponse for Body { fn into_response(self) -> Response { - Response::new(body::boxed(self)) + Response::new(self) } } @@ -243,7 +192,7 @@ impl IntoResponse for String { impl IntoResponse for Cow<'static, str> { fn into_response(self) -> Response { - let mut res = Full::from(self).into_response(); + let mut res = Body::from(self).into_response(); res.headers_mut().insert( header::CONTENT_TYPE, HeaderValue::from_static(mime::TEXT_PLAIN_UTF_8.as_ref()), @@ -254,7 +203,7 @@ impl IntoResponse for Cow<'static, str> { impl IntoResponse for Bytes { fn into_response(self) -> Response { - let mut res = Full::from(self).into_response(); + let mut res = Body::from(self).into_response(); res.headers_mut().insert( header::CONTENT_TYPE, HeaderValue::from_static(mime::APPLICATION_OCTET_STREAM.as_ref()), @@ -276,7 +225,7 @@ where { fn into_response(self) -> Response { let (first, second) = self.into_inner(); - let mut res = Response::new(body::boxed(BytesChainBody { + let mut res = Response::new(Body::new(BytesChainBody { first: Some(first), second: Some(second), })); @@ -368,7 +317,7 @@ impl IntoResponse for Vec { impl IntoResponse for Cow<'static, [u8]> { fn into_response(self) -> Response { - let mut res = Full::from(self).into_response(); + let mut res = Body::from(self).into_response(); res.headers_mut().insert( header::CONTENT_TYPE, HeaderValue::from_static(mime::APPLICATION_OCTET_STREAM.as_ref()), diff --git a/axum-core/src/response/mod.rs b/axum-core/src/response/mod.rs index d66dfec510..b06f072f19 100644 --- a/axum-core/src/response/mod.rs +++ b/axum-core/src/response/mod.rs @@ -4,7 +4,7 @@ //! //! [`axum::response`]: https://docs.rs/axum/latest/axum/response/index.html -use crate::body::BoxBody; +use crate::body::Body; mod append_headers; mod into_response; @@ -16,9 +16,9 @@ pub use self::{ into_response_parts::{IntoResponseParts, ResponseParts, TryIntoHeaderError}, }; -/// Type alias for [`http::Response`] whose body type defaults to [`BoxBody`], the most common body +/// Type alias for [`http::Response`] whose body type defaults to [`Body`], the most common body /// type used with axum. -pub type Response = http::Response; +pub type Response = http::Response; /// An [`IntoResponse`]-based result type that uses [`ErrorResponse`] as the error type. /// diff --git a/axum-extra/CHANGELOG.md b/axum-extra/CHANGELOG.md index 67955a67ea..eed4d039fb 100644 --- a/axum-extra/CHANGELOG.md +++ b/axum-extra/CHANGELOG.md @@ -7,7 +7,9 @@ and this project adheres to [Semantic Versioning]. # Unreleased -- None. +- **added:** Added `TypedHeader` which used to be in `axum` ([#1850]) + +[#1850]: https://github.com/tokio-rs/axum/pull/1850 # 0.7.4 (18. April, 2023) diff --git a/axum-extra/Cargo.toml b/axum-extra/Cargo.toml index dca9f07d66..e177d4ab49 100644 --- a/axum-extra/Cargo.toml +++ b/axum-extra/Cargo.toml @@ -31,6 +31,7 @@ json-lines = [ multipart = ["dep:multer"] protobuf = ["dep:prost"] query = ["dep:serde_html_form"] +typed-header = ["dep:headers"] typed-routing = ["dep:axum-macros", "dep:percent-encoding", "dep:serde_html_form", "dep:form_urlencoded"] [dependencies] @@ -53,6 +54,7 @@ tower-service = "0.3" axum-macros = { path = "../axum-macros", version = "0.3.7", optional = true } cookie = { package = "cookie", version = "0.17", features = ["percent-encode"], optional = true } form_urlencoded = { version = "1.1.0", optional = true } +headers = { version = "0.3.8", optional = true } multer = { version = "2.0.0", optional = true } percent-encoding = { version = "2.1", optional = true } prost = { version = "0.11", optional = true } @@ -62,8 +64,8 @@ tokio-stream = { version = "0.1.9", optional = true } tokio-util = { version = "0.7", optional = true } [dev-dependencies] -axum = { path = "../axum", version = "0.6.0", features = ["headers"] } -axum-macros = { path = "../axum-macros", version = "0.3.7", features = ["__private"] } +axum = { path = "../axum", version = "0.6.0" } +futures = "0.3" http-body = "0.4.4" hyper = "0.14" reqwest = { version = "0.11", default-features = false, features = ["json", "stream", "multipart"] } @@ -86,9 +88,10 @@ allowed = [ "cookie", "futures_core", "futures_util", + "headers", + "headers_core", "http", "http_body", - "hyper", "prost", "serde", "tokio", diff --git a/axum-extra/src/body/async_read_body.rs b/axum-extra/src/body/async_read_body.rs index 5ea0fc59c5..ce87e43693 100644 --- a/axum-extra/src/body/async_read_body.rs +++ b/axum-extra/src/body/async_read_body.rs @@ -1,5 +1,5 @@ use axum::{ - body::{self, Bytes, HttpBody, StreamBody}, + body::{Body, Bytes, HttpBody}, http::HeaderMap, response::{IntoResponse, Response}, Error, @@ -47,28 +47,25 @@ pin_project! { #[cfg(feature = "async-read-body")] #[derive(Debug)] #[must_use] - pub struct AsyncReadBody { + pub struct AsyncReadBody { #[pin] - read: StreamBody>, + body: Body, } } -impl AsyncReadBody { +impl AsyncReadBody { /// Create a new `AsyncReadBody`. - pub fn new(read: R) -> Self + pub fn new(read: R) -> Self where R: AsyncRead + Send + 'static, { Self { - read: StreamBody::new(ReaderStream::new(read)), + body: Body::from_stream(ReaderStream::new(read)), } } } -impl HttpBody for AsyncReadBody -where - R: AsyncRead + Send + 'static, -{ +impl HttpBody for AsyncReadBody { type Data = Bytes; type Error = Error; @@ -76,22 +73,19 @@ where self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll>> { - self.project().read.poll_data(cx) + self.project().body.poll_data(cx) } fn poll_trailers( self: Pin<&mut Self>, - _cx: &mut Context<'_>, + cx: &mut Context<'_>, ) -> Poll, Self::Error>> { - Poll::Ready(Ok(None)) + self.project().body.poll_trailers(cx) } } -impl IntoResponse for AsyncReadBody -where - R: AsyncRead + Send + 'static, -{ +impl IntoResponse for AsyncReadBody { fn into_response(self) -> Response { - Response::new(body::boxed(self)) + self.body.into_response() } } diff --git a/axum-extra/src/extract/cached.rs b/axum-extra/src/extract/cached.rs index 35fbe32474..6f7d6227b7 100644 --- a/axum-extra/src/extract/cached.rs +++ b/axum-extra/src/extract/cached.rs @@ -21,7 +21,6 @@ use http::request::Parts; /// use axum::{ /// async_trait, /// extract::FromRequestParts, -/// body::BoxBody, /// response::{IntoResponse, Response}, /// http::{StatusCode, request::Parts}, /// }; diff --git a/axum-extra/src/extract/cookie/mod.rs b/axum-extra/src/extract/cookie/mod.rs index 175bf9e60d..e0b84c7cbb 100644 --- a/axum-extra/src/extract/cookie/mod.rs +++ b/axum-extra/src/extract/cookie/mod.rs @@ -41,12 +41,14 @@ pub use cookie::Key; /// use axum::{ /// Router, /// routing::{post, get}, -/// extract::TypedHeader, /// response::{IntoResponse, Redirect}, -/// headers::authorization::{Authorization, Bearer}, /// http::StatusCode, /// }; -/// use axum_extra::extract::cookie::{CookieJar, Cookie}; +/// use axum_extra::{ +/// TypedHeader, +/// headers::authorization::{Authorization, Bearer}, +/// extract::cookie::{CookieJar, Cookie}, +/// }; /// /// async fn create_session( /// TypedHeader(auth): TypedHeader>, @@ -255,7 +257,7 @@ mod tests { custom_key: CustomKey(Key::generate()), }; - let app = Router::<_, Body>::new() + let app = Router::new() .route("/set", get(set_cookie)) .route("/get", get(get_cookie)) .route("/remove", get(remove_cookie)) @@ -352,7 +354,7 @@ mod tests { custom_key: CustomKey(Key::generate()), }; - let app = Router::<_, Body>::new() + let app = Router::new() .route("/get", get(get_cookie)) .with_state(state); diff --git a/axum-extra/src/extract/cookie/private.rs b/axum-extra/src/extract/cookie/private.rs index c1b55dbdcd..381735f166 100644 --- a/axum-extra/src/extract/cookie/private.rs +++ b/axum-extra/src/extract/cookie/private.rs @@ -23,12 +23,15 @@ use std::{convert::Infallible, fmt, marker::PhantomData}; /// use axum::{ /// Router, /// routing::{post, get}, -/// extract::{TypedHeader, FromRef}, +/// extract::FromRef, /// response::{IntoResponse, Redirect}, -/// headers::authorization::{Authorization, Bearer}, /// http::StatusCode, /// }; -/// use axum_extra::extract::cookie::{PrivateCookieJar, Cookie, Key}; +/// use axum_extra::{ +/// TypedHeader, +/// headers::authorization::{Authorization, Bearer}, +/// extract::cookie::{PrivateCookieJar, Cookie, Key}, +/// }; /// /// async fn set_secret( /// jar: PrivateCookieJar, diff --git a/axum-extra/src/extract/cookie/signed.rs b/axum-extra/src/extract/cookie/signed.rs index 911082f155..6025d37cba 100644 --- a/axum-extra/src/extract/cookie/signed.rs +++ b/axum-extra/src/extract/cookie/signed.rs @@ -24,12 +24,15 @@ use std::{convert::Infallible, fmt, marker::PhantomData}; /// use axum::{ /// Router, /// routing::{post, get}, -/// extract::{TypedHeader, FromRef}, +/// extract::FromRef, /// response::{IntoResponse, Redirect}, -/// headers::authorization::{Authorization, Bearer}, /// http::StatusCode, /// }; -/// use axum_extra::extract::cookie::{SignedCookieJar, Cookie, Key}; +/// use axum_extra::{ +/// TypedHeader, +/// headers::authorization::{Authorization, Bearer}, +/// extract::cookie::{SignedCookieJar, Cookie, Key}, +/// }; /// /// async fn create_session( /// TypedHeader(auth): TypedHeader>, diff --git a/axum-extra/src/extract/form.rs b/axum-extra/src/extract/form.rs index 570b9126ce..d7ee6f9842 100644 --- a/axum-extra/src/extract/form.rs +++ b/axum-extra/src/extract/form.rs @@ -1,11 +1,10 @@ use axum::{ async_trait, - body::HttpBody, - extract::{rejection::RawFormRejection, FromRequest, RawForm}, + extract::{rejection::RawFormRejection, FromRequest, RawForm, Request}, response::{IntoResponse, Response}, - BoxError, Error, RequestExt, + Error, RequestExt, }; -use http::{Request, StatusCode}; +use http::StatusCode; use serde::de::DeserializeOwned; use std::fmt; @@ -46,17 +45,14 @@ pub struct Form(pub T); axum_core::__impl_deref!(Form); #[async_trait] -impl FromRequest for Form +impl FromRequest for Form where T: DeserializeOwned, - B: HttpBody + Send + 'static, - B::Data: Send, - B::Error: Into, S: Send + Sync, { type Rejection = FormRejection; - async fn from_request(req: Request, _state: &S) -> Result { + async fn from_request(req: Request, _state: &S) -> Result { let RawForm(bytes) = req .extract() .await diff --git a/axum-extra/src/extract/mod.rs b/axum-extra/src/extract/mod.rs index 923fe456f9..c7946413a8 100644 --- a/axum-extra/src/extract/mod.rs +++ b/axum-extra/src/extract/mod.rs @@ -39,3 +39,7 @@ pub use self::multipart::Multipart; #[cfg(feature = "json-lines")] #[doc(no_inline)] pub use crate::json_lines::JsonLines; + +#[cfg(feature = "typed-header")] +#[doc(no_inline)] +pub use crate::typed_header::TypedHeader; diff --git a/axum-extra/src/extract/multipart.rs b/axum-extra/src/extract/multipart.rs index 83c4934fab..b62eb92337 100644 --- a/axum-extra/src/extract/multipart.rs +++ b/axum-extra/src/extract/multipart.rs @@ -4,10 +4,10 @@ use axum::{ async_trait, - body::{Bytes, HttpBody}, - extract::{BodyStream, FromRequest}, + body::{Body, Bytes}, + extract::FromRequest, response::{IntoResponse, Response}, - BoxError, RequestExt, + RequestExt, }; use futures_util::stream::Stream; use http::{ @@ -91,22 +91,18 @@ pub struct Multipart { } #[async_trait] -impl FromRequest for Multipart +impl FromRequest for Multipart where - B: HttpBody + Send + 'static, - B::Data: Into, - B::Error: Into, S: Send + Sync, { type Rejection = MultipartRejection; - async fn from_request(req: Request, state: &S) -> Result { + async fn from_request(req: Request, _state: &S) -> Result { let boundary = parse_boundary(req.headers()).ok_or(InvalidBoundary)?; - let stream_result = match req.with_limited_body() { - Ok(limited) => BodyStream::from_request(limited, state).await, - Err(unlimited) => BodyStream::from_request(unlimited, state).await, + let stream = match req.with_limited_body() { + Ok(limited) => Body::new(limited), + Err(unlimited) => unlimited.into_body(), }; - let stream = stream_result.unwrap_or_else(|err| match err {}); let multipart = multer::Multipart::new(stream, boundary); Ok(Self { inner: multipart }) } @@ -414,9 +410,7 @@ impl std::error::Error for InvalidBoundary {} mod tests { use super::*; use crate::test_helpers::*; - use axum::{ - body::Body, extract::DefaultBodyLimit, response::IntoResponse, routing::post, Router, - }; + use axum::{extract::DefaultBodyLimit, response::IntoResponse, routing::post, Router}; #[tokio::test] async fn content_type_with_encoding() { @@ -452,7 +446,7 @@ mod tests { // No need for this to be a #[test], we just want to make sure it compiles fn _multipart_from_request_limited() { async fn handler(_: Multipart) {} - let _app: Router<(), http_body::Limited> = Router::new().route("/", post(handler)); + let _app: Router<()> = Router::new().route("/", post(handler)); } #[tokio::test] diff --git a/axum-extra/src/extract/query.rs b/axum-extra/src/extract/query.rs index 43be2ec787..304d72b87b 100644 --- a/axum-extra/src/extract/query.rs +++ b/axum-extra/src/extract/query.rs @@ -41,9 +41,7 @@ use std::fmt; /// } /// /// let app = Router::new().route("/list_things", get(list_things)); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` /// /// If the query string cannot be parsed it will reject the request with a `400 diff --git a/axum-extra/src/extract/with_rejection.rs b/axum-extra/src/extract/with_rejection.rs index f3a0f04e87..1227a1ab13 100644 --- a/axum-extra/src/extract/with_rejection.rs +++ b/axum-extra/src/extract/with_rejection.rs @@ -1,8 +1,7 @@ use axum::async_trait; -use axum::extract::{FromRequest, FromRequestParts}; +use axum::extract::{FromRequest, FromRequestParts, Request}; use axum::response::IntoResponse; use http::request::Parts; -use http::Request; use std::fmt::Debug; use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; @@ -109,16 +108,15 @@ impl DerefMut for WithRejection { } #[async_trait] -impl FromRequest for WithRejection +impl FromRequest for WithRejection where - B: Send + 'static, S: Send + Sync, - E: FromRequest, + E: FromRequest, R: From + IntoResponse, { type Rejection = R; - async fn from_request(req: Request, state: &S) -> Result { + async fn from_request(req: Request, state: &S) -> Result { let extractor = E::from_request(req, state).await?; Ok(WithRejection(extractor, PhantomData)) } @@ -141,6 +139,7 @@ where #[cfg(test)] mod tests { + use axum::body::Body; use axum::extract::FromRequestParts; use axum::http::Request; use axum::response::Response; @@ -180,7 +179,7 @@ mod tests { } } - let req = Request::new(()); + let req = Request::new(Body::empty()); let result = WithRejection::::from_request(req, &()).await; assert!(matches!(result, Err(TestRejection))); diff --git a/axum-extra/src/handler/mod.rs b/axum-extra/src/handler/mod.rs index 305c9c8ccf..d017b41ef6 100644 --- a/axum-extra/src/handler/mod.rs +++ b/axum-extra/src/handler/mod.rs @@ -1,5 +1,7 @@ //! Additional handler utilities. +use axum::body::Body; +use axum::extract::Request; use axum::{ extract::FromRequest, handler::Handler, @@ -19,15 +21,15 @@ pub use self::or::Or; /// /// The drawbacks of this trait is that you cannot apply middleware to individual handlers like you /// can with [`Handler::layer`]. -pub trait HandlerCallWithExtractors: Sized { +pub trait HandlerCallWithExtractors: Sized { /// The type of future calling this handler returns. type Future: Future + Send + 'static; /// Call the handler with the extracted inputs. - fn call(self, extractors: T, state: S) -> >::Future; + fn call(self, extractors: T, state: S) -> >::Future; /// Conver this `HandlerCallWithExtractors` into [`Handler`]. - fn into_handler(self) -> IntoHandler { + fn into_handler(self) -> IntoHandler { IntoHandler { handler: self, _marker: PhantomData, @@ -102,9 +104,9 @@ pub trait HandlerCallWithExtractors: Sized { /// ); /// # let _: Router = app; /// ``` - fn or(self, rhs: R) -> Or + fn or(self, rhs: R) -> Or where - R: HandlerCallWithExtractors, + R: HandlerCallWithExtractors, { Or { lhs: self, @@ -117,7 +119,7 @@ pub trait HandlerCallWithExtractors: Sized { macro_rules! impl_handler_call_with { ( $($ty:ident),* $(,)? ) => { #[allow(non_snake_case)] - impl HandlerCallWithExtractors<($($ty,)*), S, B> for F + impl HandlerCallWithExtractors<($($ty,)*), S> for F where F: FnOnce($($ty,)*) -> Fut, Fut: Future + Send + 'static, @@ -130,7 +132,7 @@ macro_rules! impl_handler_call_with { self, ($($ty,)*): ($($ty,)*), _state: S, - ) -> >::Future { + ) -> >::Future { self($($ty,)*).map(IntoResponse::into_response) } } @@ -159,22 +161,22 @@ impl_handler_call_with!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, /// /// Created with [`HandlerCallWithExtractors::into_handler`]. #[allow(missing_debug_implementations)] -pub struct IntoHandler { +pub struct IntoHandler { handler: H, - _marker: PhantomData (T, S, B)>, + _marker: PhantomData (T, S)>, } -impl Handler for IntoHandler +impl Handler for IntoHandler where - H: HandlerCallWithExtractors + Clone + Send + 'static, - T: FromRequest + Send + 'static, + H: HandlerCallWithExtractors + Clone + Send + 'static, + T: FromRequest + Send + 'static, T::Rejection: Send, - B: Send + 'static, S: Send + Sync + 'static, { type Future = BoxFuture<'static, Response>; - fn call(self, req: http::Request, state: S) -> Self::Future { + fn call(self, req: Request, state: S) -> Self::Future { + let req = req.map(Body::new); Box::pin(async move { match T::from_request(req, &state).await { Ok(t) => self.handler.call(t, state).await, @@ -184,9 +186,9 @@ where } } -impl Copy for IntoHandler where H: Copy {} +impl Copy for IntoHandler where H: Copy {} -impl Clone for IntoHandler +impl Clone for IntoHandler where H: Clone, { diff --git a/axum-extra/src/handler/or.rs b/axum-extra/src/handler/or.rs index 2ef24e7145..7b78fe3d73 100644 --- a/axum-extra/src/handler/or.rs +++ b/axum-extra/src/handler/or.rs @@ -1,9 +1,8 @@ use super::HandlerCallWithExtractors; use crate::either::Either; use axum::{ - extract::{FromRequest, FromRequestParts}, + extract::{FromRequest, FromRequestParts, Request}, handler::Handler, - http::Request, response::{IntoResponse, Response}, }; use futures_util::future::{BoxFuture, Either as EitherFuture, FutureExt, Map}; @@ -14,19 +13,18 @@ use std::{future::Future, marker::PhantomData}; /// /// Created with [`HandlerCallWithExtractors::or`](super::HandlerCallWithExtractors::or). #[allow(missing_debug_implementations)] -pub struct Or { +pub struct Or { pub(super) lhs: L, pub(super) rhs: R, - pub(super) _marker: PhantomData (Lt, Rt, S, B)>, + pub(super) _marker: PhantomData (Lt, Rt, S)>, } -impl HandlerCallWithExtractors, S, B> for Or +impl HandlerCallWithExtractors, S> for Or where - L: HandlerCallWithExtractors + Send + 'static, - R: HandlerCallWithExtractors + Send + 'static, + L: HandlerCallWithExtractors + Send + 'static, + R: HandlerCallWithExtractors + Send + 'static, Rt: Send + 'static, Lt: Send + 'static, - B: Send + 'static, { // this puts `futures_util` in our public API but thats fine in axum-extra type Future = EitherFuture< @@ -38,7 +36,7 @@ where self, extractors: Either, state: S, - ) -> , S, B>>::Future { + ) -> , S>>::Future { match extractors { Either::E1(lt) => self .lhs @@ -54,21 +52,20 @@ where } } -impl Handler<(M, Lt, Rt), S, B> for Or +impl Handler<(M, Lt, Rt), S> for Or where - L: HandlerCallWithExtractors + Clone + Send + 'static, - R: HandlerCallWithExtractors + Clone + Send + 'static, + L: HandlerCallWithExtractors + Clone + Send + 'static, + R: HandlerCallWithExtractors + Clone + Send + 'static, Lt: FromRequestParts + Send + 'static, - Rt: FromRequest + Send + 'static, + Rt: FromRequest + Send + 'static, Lt::Rejection: Send, Rt::Rejection: Send, - B: Send + 'static, S: Send + Sync + 'static, { // this puts `futures_util` in our public API but thats fine in axum-extra type Future = BoxFuture<'static, Response>; - fn call(self, req: Request, state: S) -> Self::Future { + fn call(self, req: Request, state: S) -> Self::Future { Box::pin(async move { let (mut parts, body) = req.into_parts(); @@ -86,14 +83,14 @@ where } } -impl Copy for Or +impl Copy for Or where L: Copy, R: Copy, { } -impl Clone for Or +impl Clone for Or where L: Clone, R: Clone, diff --git a/axum-extra/src/json_lines.rs b/axum-extra/src/json_lines.rs index 8b04825f2c..7cf47b04a3 100644 --- a/axum-extra/src/json_lines.rs +++ b/axum-extra/src/json_lines.rs @@ -2,14 +2,13 @@ use axum::{ async_trait, - body::{HttpBody, StreamBody}, - extract::FromRequest, + body::Body, + extract::{FromRequest, Request}, response::{IntoResponse, Response}, BoxError, }; -use bytes::{BufMut, Bytes, BytesMut}; +use bytes::{BufMut, BytesMut}; use futures_util::stream::{BoxStream, Stream, TryStream, TryStreamExt}; -use http::Request; use pin_project_lite::pin_project; use serde::{de::DeserializeOwned, Serialize}; use std::{ @@ -101,26 +100,19 @@ impl JsonLines { } #[async_trait] -impl FromRequest for JsonLines +impl FromRequest for JsonLines where - B: HttpBody + Send + 'static, - B::Data: Into, - B::Error: Into, T: DeserializeOwned, S: Send + Sync, { type Rejection = Infallible; - async fn from_request(req: Request, _state: &S) -> Result { + async fn from_request(req: Request, _state: &S) -> Result { // `Stream::lines` isn't a thing so we have to convert it into an `AsyncRead` // so we can call `AsyncRead::lines` and then convert it back to a `Stream` - let body = BodyStream { - body: req.into_body(), - }; + let body = req.into_body(); - let stream = body - .map_ok(Into::into) - .map_err(|err| io::Error::new(io::ErrorKind::Other, err)); + let stream = TryStreamExt::map_err(body, |err| io::Error::new(io::ErrorKind::Other, err)); let read = StreamReader::new(stream); let lines_stream = LinesStream::new(read.lines()); @@ -140,26 +132,6 @@ where } } -// like `axum::extract::BodyStream` except it doesn't box the inner body -// we don't need that since we box the final stream in `Inner::Extractor` -pin_project! { - struct BodyStream { - #[pin] - body: B, - } -} - -impl Stream for BodyStream -where - B: HttpBody + Send + 'static, -{ - type Item = Result; - - fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - self.project().body.poll_data(cx) - } -} - impl Stream for JsonLines { type Item = Result; @@ -193,7 +165,7 @@ where buf.write_all(b"\n")?; Ok::<_, BoxError>(buf.into_inner().freeze()) }); - let stream = StreamBody::new(stream); + let stream = Body::from_stream(stream); // there is no consensus around mime type yet // https://github.com/wardi/jsonlines/issues/36 diff --git a/axum-extra/src/lib.rs b/axum-extra/src/lib.rs index a964de3753..e6f9e87981 100644 --- a/axum-extra/src/lib.rs +++ b/axum-extra/src/lib.rs @@ -21,6 +21,7 @@ //! `protobuf` | Enables the `Protobuf` extractor and response | No //! `query` | Enables the `Query` extractor | No //! `typed-routing` | Enables the `TypedPath` routing utilities | No +//! `typed-header` | Enables the `TypedHeader` extractor and response | No //! //! [`axum`]: https://crates.io/crates/axum @@ -80,6 +81,17 @@ pub mod routing; #[cfg(feature = "json-lines")] pub mod json_lines; +#[cfg(feature = "typed-header")] +pub mod typed_header; + +#[cfg(feature = "typed-header")] +#[doc(no_inline)] +pub use headers; + +#[cfg(feature = "typed-header")] +#[doc(inline)] +pub use typed_header::TypedHeader; + #[cfg(feature = "protobuf")] pub mod protobuf; @@ -105,7 +117,7 @@ use axum_macros::__private_axum_test as test; pub(crate) mod test_helpers { #![allow(unused_imports)] - use axum::{body::HttpBody, BoxError, Router}; + use axum::{extract::Request, response::Response, serve}; mod test_client { #![allow(dead_code)] diff --git a/axum-extra/src/protobuf.rs b/axum-extra/src/protobuf.rs index 1750c521c0..e3c4b51df5 100644 --- a/axum-extra/src/protobuf.rs +++ b/axum-extra/src/protobuf.rs @@ -2,13 +2,11 @@ use axum::{ async_trait, - body::{Bytes, HttpBody}, - extract::{rejection::BytesRejection, FromRequest}, + extract::{rejection::BytesRejection, FromRequest, Request}, response::{IntoResponse, Response}, - BoxError, }; -use bytes::BytesMut; -use http::{Request, StatusCode}; +use bytes::{Bytes, BytesMut}; +use http::StatusCode; use prost::Message; /// A Protocol Buffer message extractor and response. @@ -47,9 +45,7 @@ use prost::Message; /// } /// /// let app = Router::new().route("/users", post(create_user)); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` /// /// # As response @@ -87,9 +83,7 @@ use prost::Message; /// } /// /// let app = Router::new().route("/users/:id", get(get_user)); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` #[derive(Debug, Clone, Copy, Default)] #[cfg_attr(docsrs, doc(cfg(feature = "protobuf")))] @@ -97,17 +91,14 @@ use prost::Message; pub struct Protobuf(pub T); #[async_trait] -impl FromRequest for Protobuf +impl FromRequest for Protobuf where T: Message + Default, - B: HttpBody + Send + 'static, - B::Data: Send, - B::Error: Into, S: Send + Sync, { type Rejection = ProtobufRejection; - async fn from_request(req: Request, state: &S) -> Result { + async fn from_request(req: Request, state: &S) -> Result { let mut bytes = Bytes::from_request(req, state).await?; match T::decode(&mut bytes) { @@ -277,16 +268,16 @@ mod tests { result: String, } - let app = Router::new().route( - "/", - post(|input: Protobuf| async move { - let output = Output { - result: input.foo.to_owned(), - }; + #[axum::debug_handler] + async fn handler(input: Protobuf) -> Protobuf { + let output = Output { + result: input.foo.to_owned(), + }; - Protobuf(output) - }), - ); + Protobuf(output) + } + + let app = Router::new().route("/", post(handler)); let input = Input { foo: "bar".to_owned(), diff --git a/axum-extra/src/response/mod.rs b/axum-extra/src/response/mod.rs index 8bf9c43cda..dda382cf02 100644 --- a/axum-extra/src/response/mod.rs +++ b/axum-extra/src/response/mod.rs @@ -88,3 +88,7 @@ mime_response! { Wasm, "application/wasm", } + +#[cfg(feature = "typed-header")] +#[doc(no_inline)] +pub use crate::typed_header::TypedHeader; diff --git a/axum-extra/src/routing/mod.rs b/axum-extra/src/routing/mod.rs index f65ddf5c92..40cb336df8 100644 --- a/axum-extra/src/routing/mod.rs +++ b/axum-extra/src/routing/mod.rs @@ -1,7 +1,7 @@ //! Additional types for defining routes. use axum::{ - http::Request, + extract::Request, response::{IntoResponse, Redirect, Response}, routing::{any, MethodRouter}, Router, @@ -26,7 +26,7 @@ pub use axum_macros::TypedPath; pub use self::typed::{SecondElementIs, TypedPath}; /// Extension trait that adds additional methods to [`Router`]. -pub trait RouterExt: sealed::Sealed { +pub trait RouterExt: sealed::Sealed { /// Add a typed `GET` route to the router. /// /// The path will be inferred from the first argument to the handler function which must @@ -36,7 +36,7 @@ pub trait RouterExt: sealed::Sealed { #[cfg(feature = "typed-routing")] fn typed_get(self, handler: H) -> Self where - H: axum::handler::Handler, + H: axum::handler::Handler, T: SecondElementIs

+ 'static, P: TypedPath; @@ -49,7 +49,7 @@ pub trait RouterExt: sealed::Sealed { #[cfg(feature = "typed-routing")] fn typed_delete(self, handler: H) -> Self where - H: axum::handler::Handler, + H: axum::handler::Handler, T: SecondElementIs

+ 'static, P: TypedPath; @@ -62,7 +62,7 @@ pub trait RouterExt: sealed::Sealed { #[cfg(feature = "typed-routing")] fn typed_head(self, handler: H) -> Self where - H: axum::handler::Handler, + H: axum::handler::Handler, T: SecondElementIs

+ 'static, P: TypedPath; @@ -75,7 +75,7 @@ pub trait RouterExt: sealed::Sealed { #[cfg(feature = "typed-routing")] fn typed_options(self, handler: H) -> Self where - H: axum::handler::Handler, + H: axum::handler::Handler, T: SecondElementIs

+ 'static, P: TypedPath; @@ -88,7 +88,7 @@ pub trait RouterExt: sealed::Sealed { #[cfg(feature = "typed-routing")] fn typed_patch(self, handler: H) -> Self where - H: axum::handler::Handler, + H: axum::handler::Handler, T: SecondElementIs

+ 'static, P: TypedPath; @@ -101,7 +101,7 @@ pub trait RouterExt: sealed::Sealed { #[cfg(feature = "typed-routing")] fn typed_post(self, handler: H) -> Self where - H: axum::handler::Handler, + H: axum::handler::Handler, T: SecondElementIs

+ 'static, P: TypedPath; @@ -114,7 +114,7 @@ pub trait RouterExt: sealed::Sealed { #[cfg(feature = "typed-routing")] fn typed_put(self, handler: H) -> Self where - H: axum::handler::Handler, + H: axum::handler::Handler, T: SecondElementIs

+ 'static, P: TypedPath; @@ -127,7 +127,7 @@ pub trait RouterExt: sealed::Sealed { #[cfg(feature = "typed-routing")] fn typed_trace(self, handler: H) -> Self where - H: axum::handler::Handler, + H: axum::handler::Handler, T: SecondElementIs

+ 'static, P: TypedPath; @@ -156,7 +156,7 @@ pub trait RouterExt: sealed::Sealed { /// .route_with_tsr("/bar/", get(|| async {})); /// # let _: Router = app; /// ``` - fn route_with_tsr(self, path: &str, method_router: MethodRouter) -> Self + fn route_with_tsr(self, path: &str, method_router: MethodRouter) -> Self where Self: Sized; @@ -165,21 +165,20 @@ pub trait RouterExt: sealed::Sealed { /// This works like [`RouterExt::route_with_tsr`] but accepts any [`Service`]. fn route_service_with_tsr(self, path: &str, service: T) -> Self where - T: Service, Error = Infallible> + Clone + Send + 'static, + T: Service + Clone + Send + 'static, T::Response: IntoResponse, T::Future: Send + 'static, Self: Sized; } -impl RouterExt for Router +impl RouterExt for Router where - B: axum::body::HttpBody + Send + 'static, S: Clone + Send + Sync + 'static, { #[cfg(feature = "typed-routing")] fn typed_get(self, handler: H) -> Self where - H: axum::handler::Handler, + H: axum::handler::Handler, T: SecondElementIs

+ 'static, P: TypedPath, { @@ -189,7 +188,7 @@ where #[cfg(feature = "typed-routing")] fn typed_delete(self, handler: H) -> Self where - H: axum::handler::Handler, + H: axum::handler::Handler, T: SecondElementIs

+ 'static, P: TypedPath, { @@ -199,7 +198,7 @@ where #[cfg(feature = "typed-routing")] fn typed_head(self, handler: H) -> Self where - H: axum::handler::Handler, + H: axum::handler::Handler, T: SecondElementIs

+ 'static, P: TypedPath, { @@ -209,7 +208,7 @@ where #[cfg(feature = "typed-routing")] fn typed_options(self, handler: H) -> Self where - H: axum::handler::Handler, + H: axum::handler::Handler, T: SecondElementIs

+ 'static, P: TypedPath, { @@ -219,7 +218,7 @@ where #[cfg(feature = "typed-routing")] fn typed_patch(self, handler: H) -> Self where - H: axum::handler::Handler, + H: axum::handler::Handler, T: SecondElementIs

+ 'static, P: TypedPath, { @@ -229,7 +228,7 @@ where #[cfg(feature = "typed-routing")] fn typed_post(self, handler: H) -> Self where - H: axum::handler::Handler, + H: axum::handler::Handler, T: SecondElementIs

+ 'static, P: TypedPath, { @@ -239,7 +238,7 @@ where #[cfg(feature = "typed-routing")] fn typed_put(self, handler: H) -> Self where - H: axum::handler::Handler, + H: axum::handler::Handler, T: SecondElementIs

+ 'static, P: TypedPath, { @@ -249,7 +248,7 @@ where #[cfg(feature = "typed-routing")] fn typed_trace(self, handler: H) -> Self where - H: axum::handler::Handler, + H: axum::handler::Handler, T: SecondElementIs

+ 'static, P: TypedPath, { @@ -257,7 +256,7 @@ where } #[track_caller] - fn route_with_tsr(mut self, path: &str, method_router: MethodRouter) -> Self + fn route_with_tsr(mut self, path: &str, method_router: MethodRouter) -> Self where Self: Sized, { @@ -269,7 +268,7 @@ where #[track_caller] fn route_service_with_tsr(mut self, path: &str, service: T) -> Self where - T: Service, Error = Infallible> + Clone + Send + 'static, + T: Service + Clone + Send + 'static, T::Response: IntoResponse, T::Future: Send + 'static, Self: Sized, @@ -287,9 +286,8 @@ fn validate_tsr_path(path: &str) { } } -fn add_tsr_redirect_route(router: Router, path: &str) -> Router +fn add_tsr_redirect_route(router: Router, path: &str) -> Router where - B: axum::body::HttpBody + Send + 'static, S: Clone + Send + Sync + 'static, { async fn redirect_handler(uri: Uri) -> Response { @@ -337,7 +335,7 @@ where mod sealed { pub trait Sealed {} - impl Sealed for axum::Router {} + impl Sealed for axum::Router {} } #[cfg(test)] diff --git a/axum-extra/src/routing/resource.rs b/axum-extra/src/routing/resource.rs index a4d350bbea..2ab3b9d9e8 100644 --- a/axum-extra/src/routing/resource.rs +++ b/axum-extra/src/routing/resource.rs @@ -1,5 +1,4 @@ use axum::{ - body::Body, handler::Handler, routing::{delete, get, on, post, MethodFilter, MethodRouter}, Router, @@ -34,14 +33,13 @@ use axum::{ /// ``` #[derive(Debug)] #[must_use] -pub struct Resource { +pub struct Resource { pub(crate) name: String, - pub(crate) router: Router, + pub(crate) router: Router, } -impl Resource +impl Resource where - B: axum::body::HttpBody + Send + 'static, S: Clone + Send + Sync + 'static, { /// Create a `Resource` with the given name. @@ -57,7 +55,7 @@ where /// Add a handler at `GET /{resource_name}`. pub fn index(self, handler: H) -> Self where - H: Handler, + H: Handler, T: 'static, { let path = self.index_create_path(); @@ -67,7 +65,7 @@ where /// Add a handler at `POST /{resource_name}`. pub fn create(self, handler: H) -> Self where - H: Handler, + H: Handler, T: 'static, { let path = self.index_create_path(); @@ -77,7 +75,7 @@ where /// Add a handler at `GET /{resource_name}/new`. pub fn new(self, handler: H) -> Self where - H: Handler, + H: Handler, T: 'static, { let path = format!("/{}/new", self.name); @@ -87,7 +85,7 @@ where /// Add a handler at `GET /{resource_name}/:{resource_name}_id`. pub fn show(self, handler: H) -> Self where - H: Handler, + H: Handler, T: 'static, { let path = self.show_update_destroy_path(); @@ -97,7 +95,7 @@ where /// Add a handler at `GET /{resource_name}/:{resource_name}_id/edit`. pub fn edit(self, handler: H) -> Self where - H: Handler, + H: Handler, T: 'static, { let path = format!("/{0}/:{0}_id/edit", self.name); @@ -107,7 +105,7 @@ where /// Add a handler at `PUT or PATCH /resource_name/:{resource_name}_id`. pub fn update(self, handler: H) -> Self where - H: Handler, + H: Handler, T: 'static, { let path = self.show_update_destroy_path(); @@ -117,7 +115,7 @@ where /// Add a handler at `DELETE /{resource_name}/:{resource_name}_id`. pub fn destroy(self, handler: H) -> Self where - H: Handler, + H: Handler, T: 'static, { let path = self.show_update_destroy_path(); @@ -132,14 +130,14 @@ where format!("/{0}/:{0}_id", self.name) } - fn route(mut self, path: &str, method_router: MethodRouter) -> Self { + fn route(mut self, path: &str, method_router: MethodRouter) -> Self { self.router = self.router.route(path, method_router); self } } -impl From> for Router { - fn from(resource: Resource) -> Self { +impl From> for Router { + fn from(resource: Resource) -> Self { resource.router } } @@ -148,9 +146,9 @@ impl From> for Router { mod tests { #[allow(unused_imports)] use super::*; - use axum::{extract::Path, http::Method, Router}; + use axum::{body::Body, extract::Path, http::Method, Router}; use http::Request; - use tower::{Service, ServiceExt}; + use tower::ServiceExt; #[tokio::test] async fn works() { @@ -208,10 +206,8 @@ mod tests { async fn call_route(app: &mut Router, method: Method, uri: &str) -> String { let res = app - .ready() - .await - .unwrap() - .call( + .clone() + .oneshot( Request::builder() .method(method) .uri(uri) diff --git a/axum/src/typed_header.rs b/axum-extra/src/typed_header.rs similarity index 88% rename from axum/src/typed_header.rs rename to axum-extra/src/typed_header.rs index 72b3d7e7af..4c0e4720db 100644 --- a/axum/src/typed_header.rs +++ b/axum-extra/src/typed_header.rs @@ -1,7 +1,11 @@ -use crate::extract::FromRequestParts; -use async_trait::async_trait; -use axum_core::response::{IntoResponse, IntoResponseParts, Response, ResponseParts}; -use headers::HeaderMapExt; +//! Extractor and response for typed headers. + +use axum::{ + async_trait, + extract::FromRequestParts, + response::{IntoResponse, IntoResponseParts, Response, ResponseParts}, +}; +use headers::{Header, HeaderMapExt}; use http::request::Parts; use std::convert::Infallible; @@ -14,11 +18,11 @@ use std::convert::Infallible; /// /// ```rust,no_run /// use axum::{ -/// TypedHeader, -/// headers::UserAgent, /// routing::get, /// Router, /// }; +/// use headers::UserAgent; +/// use axum_extra::TypedHeader; /// /// async fn users_teams_show( /// TypedHeader(user_agent): TypedHeader, @@ -27,19 +31,17 @@ use std::convert::Infallible; /// } /// /// let app = Router::new().route("/users/:user_id/team/:team_id", get(users_teams_show)); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` /// /// # As response /// /// ```rust /// use axum::{ -/// TypedHeader, /// response::IntoResponse, -/// headers::ContentType, /// }; +/// use headers::ContentType; +/// use axum_extra::TypedHeader; /// /// async fn handler() -> (TypedHeader, &'static str) { /// ( @@ -48,7 +50,7 @@ use std::convert::Infallible; /// ) /// } /// ``` -#[cfg(feature = "headers")] +#[cfg(feature = "typed-header")] #[derive(Debug, Clone, Copy)] #[must_use] pub struct TypedHeader(pub T); @@ -56,7 +58,7 @@ pub struct TypedHeader(pub T); #[async_trait] impl FromRequestParts for TypedHeader where - T: headers::Header, + T: Header, S: Send + Sync, { type Rejection = TypedHeaderRejection; @@ -82,7 +84,7 @@ axum_core::__impl_deref!(TypedHeader); impl IntoResponseParts for TypedHeader where - T: headers::Header, + T: Header, { type Error = Infallible; @@ -94,7 +96,7 @@ where impl IntoResponse for TypedHeader where - T: headers::Header, + T: Header, { fn into_response(self) -> Response { let mut res = ().into_response(); @@ -103,8 +105,8 @@ where } } -/// Rejection used for [`TypedHeader`](super::TypedHeader). -#[cfg(feature = "headers")] +/// Rejection used for [`TypedHeader`](TypedHeader). +#[cfg(feature = "typed-header")] #[derive(Debug)] pub struct TypedHeaderRejection { name: &'static http::header::HeaderName, @@ -124,7 +126,7 @@ impl TypedHeaderRejection { } /// Additional information regarding a [`TypedHeaderRejection`] -#[cfg(feature = "headers")] +#[cfg(feature = "typed-header")] #[derive(Debug)] #[non_exhaustive] pub enum TypedHeaderRejectionReason { @@ -165,9 +167,10 @@ impl std::error::Error for TypedHeaderRejection { #[cfg(test)] mod tests { use super::*; - use crate::{response::IntoResponse, routing::get, test_helpers::*, Router}; + use crate::test_helpers::*; + use axum::{response::IntoResponse, routing::get, Router}; - #[crate::test] + #[tokio::test] async fn typed_header() { async fn handle( TypedHeader(user_agent): TypedHeader, diff --git a/axum-macros/CHANGELOG.md b/axum-macros/CHANGELOG.md index 2e04bd75ea..5d5d5645a2 100644 --- a/axum-macros/CHANGELOG.md +++ b/axum-macros/CHANGELOG.md @@ -7,7 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 # Unreleased -- None. +- **breaking:** `#[debug_handler]` no longer accepts a `body = _` argument. The + body type is always `axum::body::Body` ([#1751]) + +[#1751]: https://github.com/tokio-rs/axum/pull/1751 # 0.3.7 (22. March, 2023) @@ -23,6 +26,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 request-consuming extractors ([#1826]) [#1826]: https://github.com/tokio-rs/axum/pull/1826 +[#1751]: https://github.com/tokio-rs/axum/pull/1751 # 0.3.5 (03. March, 2023) diff --git a/axum-macros/Cargo.toml b/axum-macros/Cargo.toml index 5599610b97..a087aff4de 100644 --- a/axum-macros/Cargo.toml +++ b/axum-macros/Cargo.toml @@ -30,8 +30,8 @@ syn = { version = "2.0", features = [ ] } [dev-dependencies] -axum = { path = "../axum", version = "0.6.0", features = ["headers", "macros"] } -axum-extra = { path = "../axum-extra", version = "0.7.0", features = ["typed-routing", "cookie-private"] } +axum = { path = "../axum", version = "0.6.0", features = ["macros"] } +axum-extra = { path = "../axum-extra", version = "0.7.0", features = ["typed-routing", "cookie-private", "typed-header"] } rustversion = "1.0" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" diff --git a/axum-macros/rust-toolchain b/axum-macros/rust-toolchain index 8141c9d1e3..a1eb1fc7a7 100644 --- a/axum-macros/rust-toolchain +++ b/axum-macros/rust-toolchain @@ -1 +1 @@ -nightly-2022-11-18 +nightly-2023-04-06 diff --git a/axum-macros/src/debug_handler.rs b/axum-macros/src/debug_handler.rs index 9b42a1af90..0f361a10cb 100644 --- a/axum-macros/src/debug_handler.rs +++ b/axum-macros/src/debug_handler.rs @@ -6,14 +6,10 @@ use crate::{ }; use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote, quote_spanned}; -use syn::{parse::Parse, parse_quote, spanned::Spanned, FnArg, ItemFn, Token, Type}; +use syn::{parse::Parse, spanned::Spanned, FnArg, ItemFn, Token, Type}; pub(crate) fn expand(attr: Attrs, item_fn: ItemFn) -> TokenStream { - let Attrs { body_ty, state_ty } = attr; - - let body_ty = body_ty - .map(second) - .unwrap_or_else(|| parse_quote!(axum::body::Body)); + let Attrs { state_ty } = attr; let mut state_ty = state_ty.map(second); @@ -47,17 +43,16 @@ pub(crate) fn expand(attr: Attrs, item_fn: ItemFn) -> TokenStream { err.unwrap_or_else(|| { let state_ty = state_ty.unwrap_or_else(|| syn::parse_quote!(())); - let check_input_order = check_input_order(&item_fn); let check_future_send = check_future_send(&item_fn); - if let Some(check_input_order) = check_input_order { + if let Some(check_input_order) = check_input_order(&item_fn) { quote! { #check_input_order #check_future_send } } else { let check_inputs_impls_from_request = - check_inputs_impls_from_request(&item_fn, &body_ty, state_ty); + check_inputs_impls_from_request(&item_fn, state_ty); quote! { #check_inputs_impls_from_request @@ -88,20 +83,16 @@ mod kw { } pub(crate) struct Attrs { - body_ty: Option<(kw::body, Type)>, state_ty: Option<(kw::state, Type)>, } impl Parse for Attrs { fn parse(input: syn::parse::ParseStream) -> syn::Result { - let mut body_ty = None; let mut state_ty = None; while !input.is_empty() { let lh = input.lookahead1(); - if lh.peek(kw::body) { - parse_assignment_attribute(input, &mut body_ty)?; - } else if lh.peek(kw::state) { + if lh.peek(kw::state) { parse_assignment_attribute(input, &mut state_ty)?; } else { return Err(lh.error()); @@ -110,7 +101,7 @@ impl Parse for Attrs { let _ = input.parse::(); } - Ok(Self { body_ty, state_ty }) + Ok(Self { state_ty }) } } @@ -183,11 +174,7 @@ fn is_self_pat_type(typed: &syn::PatType) -> bool { ident == "self" } -fn check_inputs_impls_from_request( - item_fn: &ItemFn, - body_ty: &Type, - state_ty: Type, -) -> TokenStream { +fn check_inputs_impls_from_request(item_fn: &ItemFn, state_ty: Type) -> TokenStream { let takes_self = item_fn.sig.inputs.first().map_or(false, |arg| match arg { FnArg::Receiver(_) => true, FnArg::Typed(typed) => is_self_pat_type(typed), @@ -266,11 +253,11 @@ fn check_inputs_impls_from_request( } } else if consumes_request { quote_spanned! {span=> - #ty: ::axum::extract::FromRequest<#state_ty, #body_ty> + Send + #ty: ::axum::extract::FromRequest<#state_ty> + Send } } else { quote_spanned! {span=> - #ty: ::axum::extract::FromRequest<#state_ty, #body_ty, M> + Send + #ty: ::axum::extract::FromRequest<#state_ty, M> + Send } }; @@ -379,7 +366,6 @@ fn request_consuming_type_name(ty: &Type) -> Option<&'static str> { let type_name = match &*ident.to_string() { "Json" => "Json<_>", - "BodyStream" => "BodyStream", "RawBody" => "RawBody<_>", "RawForm" => "RawForm", "Multipart" => "Multipart", diff --git a/axum-macros/src/from_request.rs b/axum-macros/src/from_request.rs index 7f6e76c9f7..e9608e7f62 100644 --- a/axum-macros/src/from_request.rs +++ b/axum-macros/src/from_request.rs @@ -19,13 +19,6 @@ pub(crate) enum Trait { } impl Trait { - fn body_type(&self) -> impl Iterator { - match self { - Trait::FromRequest => Some(parse_quote!(B)).into_iter(), - Trait::FromRequestParts => None.into_iter(), - } - } - fn via_marker_type(&self) -> Option { match self { Trait::FromRequest => Some(parse_quote!(M)), @@ -370,14 +363,12 @@ fn impl_struct_by_extracting_each_field( quote!(::axum::response::Response) }; - let impl_generics = tr - .body_type() - .chain(state.impl_generics()) + let impl_generics = state + .impl_generics() .collect::>(); let trait_generics = state .trait_generics() - .chain(tr.body_type()) .collect::>(); let state_bounds = state.bounds(); @@ -388,15 +379,12 @@ fn impl_struct_by_extracting_each_field( #[automatically_derived] impl<#impl_generics> ::axum::extract::FromRequest<#trait_generics> for #ident where - B: ::axum::body::HttpBody + ::std::marker::Send + 'static, - B::Data: ::std::marker::Send, - B::Error: ::std::convert::Into<::axum::BoxError>, #state_bounds { type Rejection = #rejection_ident; async fn from_request( - mut req: ::axum::http::Request, + mut req: ::axum::http::Request<::axum::body::Body>, state: &#state, ) -> ::std::result::Result { #trait_fn_body @@ -749,7 +737,7 @@ fn impl_struct_by_extracting_all_at_once( // struct AppState {} // ``` // - // we need to implement `impl FromRequest` but only for + // we need to implement `impl FromRequest` but only for // - `#[derive(FromRequest)]`, not `#[derive(FromRequestParts)]` // - `State`, not other extractors // @@ -760,16 +748,15 @@ fn impl_struct_by_extracting_all_at_once( None }; - let impl_generics = tr - .body_type() - .chain(via_marker_type.clone()) + let impl_generics = via_marker_type + .iter() + .cloned() .chain(state.impl_generics()) .chain(generic_ident.is_some().then(|| parse_quote!(T))) .collect::>(); let trait_generics = state .trait_generics() - .chain(tr.body_type()) .chain(via_marker_type) .collect::>(); @@ -828,13 +815,12 @@ fn impl_struct_by_extracting_all_at_once( where #via_path<#via_type_generics>: ::axum::extract::FromRequest<#trait_generics>, #rejection_bound - B: ::std::marker::Send + 'static, #state_bounds { type Rejection = #associated_rejection_type; async fn from_request( - req: ::axum::http::Request, + req: ::axum::http::Request<::axum::body::Body>, state: &#state, ) -> ::std::result::Result { ::axum::extract::FromRequest::from_request(req, state) @@ -923,14 +909,12 @@ fn impl_enum_by_extracting_all_at_once( let path_span = path.span(); - let impl_generics = tr - .body_type() - .chain(state.impl_generics()) + let impl_generics = state + .impl_generics() .collect::>(); let trait_generics = state .trait_generics() - .chain(tr.body_type()) .collect::>(); let state_bounds = state.bounds(); @@ -942,15 +926,12 @@ fn impl_enum_by_extracting_all_at_once( #[automatically_derived] impl<#impl_generics> ::axum::extract::FromRequest<#trait_generics> for #ident where - B: ::axum::body::HttpBody + ::std::marker::Send + 'static, - B::Data: ::std::marker::Send, - B::Error: ::std::convert::Into<::axum::BoxError>, #state_bounds { type Rejection = #associated_rejection_type; async fn from_request( - req: ::axum::http::Request, + req: ::axum::http::Request<::axum::body::Body>, state: &#state, ) -> ::std::result::Result { ::axum::extract::FromRequest::from_request(req, state) diff --git a/axum-macros/src/lib.rs b/axum-macros/src/lib.rs index a49383e031..e83ff75cd3 100644 --- a/axum-macros/src/lib.rs +++ b/axum-macros/src/lib.rs @@ -72,10 +72,13 @@ use from_request::Trait::{FromRequest, FromRequestParts}; /// ``` /// use axum_macros::FromRequest; /// use axum::{ -/// extract::{Extension, TypedHeader}, -/// headers::ContentType, +/// extract::Extension, /// body::Bytes, /// }; +/// use axum_extra::{ +/// TypedHeader, +/// headers::ContentType, +/// }; /// /// #[derive(FromRequest)] /// struct MyExtractor { @@ -117,10 +120,13 @@ use from_request::Trait::{FromRequest, FromRequestParts}; /// ``` /// use axum_macros::FromRequest; /// use axum::{ -/// extract::{Extension, TypedHeader}, -/// headers::ContentType, +/// extract::Extension, /// body::Bytes, /// }; +/// use axum_extra::{ +/// TypedHeader, +/// headers::ContentType, +/// }; /// /// #[derive(FromRequest)] /// struct MyExtractor { @@ -148,7 +154,7 @@ use from_request::Trait::{FromRequest, FromRequestParts}; /// ``` /// pub struct ViaExtractor(pub T); /// -/// // impl FromRequest for ViaExtractor { ... } +/// // impl FromRequest for ViaExtractor { ... } /// ``` /// /// More complex via extractors are not supported and require writing a manual implementation. @@ -159,9 +165,10 @@ use from_request::Trait::{FromRequest, FromRequestParts}; /// /// ``` /// use axum_macros::FromRequest; -/// use axum::{ -/// extract::{TypedHeader, rejection::TypedHeaderRejection}, +/// use axum_extra::{ +/// TypedHeader, /// headers::{ContentType, UserAgent}, +/// typed_header::TypedHeaderRejection, /// }; /// /// #[derive(FromRequest)] @@ -369,7 +376,10 @@ pub fn derive_from_request(item: TokenStream) -> TokenStream { /// ``` /// use axum_macros::FromRequestParts; /// use axum::{ -/// extract::{Query, TypedHeader}, +/// extract::Query, +/// }; +/// use axum_extra::{ +/// TypedHeader, /// headers::ContentType, /// }; /// use std::collections::HashMap; @@ -416,10 +426,8 @@ pub fn derive_from_request_parts(item: TokenStream) -> TokenStream { /// async fn main() { /// let app = Router::new().route("/", get(handler)); /// -/// axum::Server::bind(&"0.0.0.0:3000".parse().unwrap()) -/// .serve(app.into_make_service()) -/// .await -/// .unwrap(); +/// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); +/// axum::serve(listener, app).await.unwrap(); /// } /// /// fn handler() -> &'static str { @@ -438,10 +446,8 @@ pub fn derive_from_request_parts(item: TokenStream) -> TokenStream { /// # async fn main() { /// # let app = Router::new().route("/", get(handler)); /// # -/// # axum::Server::bind(&"0.0.0.0:3000".parse().unwrap()) -/// # .serve(app.into_make_service()) -/// # .await -/// # .unwrap(); +/// # let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); +/// # axum::serve(listener, app).await.unwrap(); /// # } /// # /// #[debug_handler] @@ -468,10 +474,8 @@ pub fn derive_from_request_parts(item: TokenStream) -> TokenStream { /// # async { /// let app = Router::new().route("/", get(handler)); /// -/// axum::Server::bind(&"0.0.0.0:3000".parse().unwrap()) -/// .serve(app.into_make_service()) -/// .await -/// .unwrap(); +/// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); +/// axum::serve(listener, app).await.unwrap(); /// # }; /// } /// @@ -481,21 +485,6 @@ pub fn derive_from_request_parts(item: TokenStream) -> TokenStream { /// } /// ``` /// -/// # Changing request body type -/// -/// By default `#[debug_handler]` assumes your request body type is `axum::body::Body`. This will -/// work for most extractors but, for example, it wont work for `Request`, -/// which only implements `FromRequest` and _not_ `FromRequest`. -/// -/// To work around that the request body type can be customized like so: -/// -/// ``` -/// use axum::{body::BoxBody, http::Request, debug_handler}; -/// -/// #[debug_handler(body = BoxBody)] -/// async fn handler(request: Request) {} -/// ``` -/// /// # Changing state type /// /// By default `#[debug_handler]` assumes your state type is `()` unless your handler has a diff --git a/axum-macros/tests/debug_handler/fail/argument_not_extractor.stderr b/axum-macros/tests/debug_handler/fail/argument_not_extractor.stderr index 360163cade..5f0e8664c8 100644 --- a/axum-macros/tests/debug_handler/fail/argument_not_extractor.stderr +++ b/axum-macros/tests/debug_handler/fail/argument_not_extractor.stderr @@ -15,8 +15,8 @@ error[E0277]: the trait bound `bool: FromRequestParts<()>` is not satisfied <(T1, T2, T3, T4, T5, T6) as FromRequestParts> <(T1, T2, T3, T4, T5, T6, T7) as FromRequestParts> <(T1, T2, T3, T4, T5, T6, T7, T8) as FromRequestParts> - and 26 others - = note: required for `bool` to implement `FromRequest<(), Body, axum_core::extract::private::ViaParts>` + and $N others + = note: required for `bool` to implement `FromRequest<(), axum_core::extract::private::ViaParts>` note: required by a bound in `__axum_macros_check_handler_0_from_request_check` --> tests/debug_handler/fail/argument_not_extractor.rs:4:23 | diff --git a/axum-macros/tests/debug_handler/fail/duplicate_args.rs b/axum-macros/tests/debug_handler/fail/duplicate_args.rs index dca335bd3c..4fc7c90fd6 100644 --- a/axum-macros/tests/debug_handler/fail/duplicate_args.rs +++ b/axum-macros/tests/debug_handler/fail/duplicate_args.rs @@ -1,9 +1,6 @@ use axum_macros::debug_handler; -#[debug_handler(body = BoxBody, body = BoxBody)] -async fn handler() {} - #[debug_handler(state = (), state = ())] -async fn handler_2() {} +async fn handler() {} fn main() {} diff --git a/axum-macros/tests/debug_handler/fail/duplicate_args.stderr b/axum-macros/tests/debug_handler/fail/duplicate_args.stderr index 694b6cb3ee..bed70f774a 100644 --- a/axum-macros/tests/debug_handler/fail/duplicate_args.stderr +++ b/axum-macros/tests/debug_handler/fail/duplicate_args.stderr @@ -1,11 +1,5 @@ -error: `body` specified more than once - --> tests/debug_handler/fail/duplicate_args.rs:3:33 - | -3 | #[debug_handler(body = BoxBody, body = BoxBody)] - | ^^^^ - error: `state` specified more than once - --> tests/debug_handler/fail/duplicate_args.rs:6:29 + --> tests/debug_handler/fail/duplicate_args.rs:3:29 | -6 | #[debug_handler(state = (), state = ())] +3 | #[debug_handler(state = (), state = ())] | ^^^^^ diff --git a/axum-macros/tests/debug_handler/fail/extract_self_mut.rs b/axum-macros/tests/debug_handler/fail/extract_self_mut.rs index d20426e22f..21ae99d6b8 100644 --- a/axum-macros/tests/debug_handler/fail/extract_self_mut.rs +++ b/axum-macros/tests/debug_handler/fail/extract_self_mut.rs @@ -1,21 +1,19 @@ use axum::{ async_trait, - extract::FromRequest, - http::Request, + extract::{Request, FromRequest}, }; use axum_macros::debug_handler; struct A; #[async_trait] -impl FromRequest for A +impl FromRequest for A where - B: Send + 'static, S: Send + Sync, { type Rejection = (); - async fn from_request(_req: Request, _state: &S) -> Result { + async fn from_request(_req: Request, _state: &S) -> Result { unimplemented!() } } diff --git a/axum-macros/tests/debug_handler/fail/extract_self_mut.stderr b/axum-macros/tests/debug_handler/fail/extract_self_mut.stderr index 1e1a9ec384..595786bf4e 100644 --- a/axum-macros/tests/debug_handler/fail/extract_self_mut.stderr +++ b/axum-macros/tests/debug_handler/fail/extract_self_mut.stderr @@ -1,5 +1,5 @@ error: Handlers must only take owned values - --> tests/debug_handler/fail/extract_self_mut.rs:25:22 + --> tests/debug_handler/fail/extract_self_mut.rs:23:22 | -25 | async fn handler(&mut self) {} +23 | async fn handler(&mut self) {} | ^^^^^^^^^ diff --git a/axum-macros/tests/debug_handler/fail/extract_self_ref.rs b/axum-macros/tests/debug_handler/fail/extract_self_ref.rs index 77940e2996..8e32811994 100644 --- a/axum-macros/tests/debug_handler/fail/extract_self_ref.rs +++ b/axum-macros/tests/debug_handler/fail/extract_self_ref.rs @@ -1,21 +1,19 @@ use axum::{ async_trait, - extract::FromRequest, - http::Request, + extract::{Request, FromRequest}, }; use axum_macros::debug_handler; struct A; #[async_trait] -impl FromRequest for A +impl FromRequest for A where - B: Send + 'static, S: Send + Sync, { type Rejection = (); - async fn from_request(_req: Request, _state: &S) -> Result { + async fn from_request(_req: Request, _state: &S) -> Result { unimplemented!() } } diff --git a/axum-macros/tests/debug_handler/fail/extract_self_ref.stderr b/axum-macros/tests/debug_handler/fail/extract_self_ref.stderr index 79f9d190f5..4c0b4950c7 100644 --- a/axum-macros/tests/debug_handler/fail/extract_self_ref.stderr +++ b/axum-macros/tests/debug_handler/fail/extract_self_ref.stderr @@ -1,5 +1,5 @@ error: Handlers must only take owned values - --> tests/debug_handler/fail/extract_self_ref.rs:25:22 + --> tests/debug_handler/fail/extract_self_ref.rs:23:22 | -25 | async fn handler(&self) {} +23 | async fn handler(&self) {} | ^^^^^ diff --git a/axum-macros/tests/debug_handler/fail/invalid_attrs.stderr b/axum-macros/tests/debug_handler/fail/invalid_attrs.stderr index 93514ebfe5..d2db79b336 100644 --- a/axum-macros/tests/debug_handler/fail/invalid_attrs.stderr +++ b/axum-macros/tests/debug_handler/fail/invalid_attrs.stderr @@ -1,4 +1,4 @@ -error: expected `body` or `state` +error: expected `state` --> tests/debug_handler/fail/invalid_attrs.rs:3:17 | 3 | #[debug_handler(foo)] diff --git a/axum-macros/tests/debug_handler/fail/json_not_deserialize.stderr b/axum-macros/tests/debug_handler/fail/json_not_deserialize.stderr index e93ae20ccd..6868e400b2 100644 --- a/axum-macros/tests/debug_handler/fail/json_not_deserialize.stderr +++ b/axum-macros/tests/debug_handler/fail/json_not_deserialize.stderr @@ -15,6 +15,6 @@ error[E0277]: the trait bound `for<'de> Struct: serde::de::Deserialize<'de>` is (T0, T1, T2, T3) and $N others = note: required for `Struct` to implement `serde::de::DeserializeOwned` - = note: required for `Json` to implement `FromRequest<(), Body>` + = note: required for `Json` to implement `FromRequest<()>` = help: see issue #48214 = help: add `#![feature(trivial_bounds)]` to the crate attributes to enable diff --git a/axum-macros/tests/debug_handler/fail/wrong_return_type.stderr b/axum-macros/tests/debug_handler/fail/wrong_return_type.stderr index 151c5f84bf..46d4673b75 100644 --- a/axum-macros/tests/debug_handler/fail/wrong_return_type.stderr +++ b/axum-macros/tests/debug_handler/fail/wrong_return_type.stderr @@ -18,4 +18,4 @@ note: required by a bound in `__axum_macros_check_handler_into_response::{closur --> tests/debug_handler/fail/wrong_return_type.rs:4:23 | 4 | async fn handler() -> bool { - | ^^^^ required by this bound in `__axum_macros_check_handler_into_response::{closure#0}::check` + | ^^^^ required by this bound in `check` diff --git a/axum-macros/tests/debug_handler/pass/different_request_body_type.rs b/axum-macros/tests/debug_handler/pass/different_request_body_type.rs deleted file mode 100644 index 715e5aec19..0000000000 --- a/axum-macros/tests/debug_handler/pass/different_request_body_type.rs +++ /dev/null @@ -1,10 +0,0 @@ -use axum::{body::BoxBody, http::Request}; -use axum_macros::debug_handler; - -#[debug_handler(body = BoxBody)] -async fn handler(_: Request) {} - -#[debug_handler(body = axum::body::BoxBody,)] -async fn handler_with_trailing_comma_and_type_path(_: Request) {} - -fn main() {} diff --git a/axum-macros/tests/debug_handler/pass/request_last.rs b/axum-macros/tests/debug_handler/pass/request_last.rs index bbfb53d28e..da1531f458 100644 --- a/axum-macros/tests/debug_handler/pass/request_last.rs +++ b/axum-macros/tests/debug_handler/pass/request_last.rs @@ -1,7 +1,7 @@ -use axum::{body::Body, extract::Extension, http::Request}; +use axum::extract::{Extension, Request}; use axum_macros::debug_handler; #[debug_handler] -async fn handler(_: Extension, _: Request) {} +async fn handler(_: Extension, _: Request) {} fn main() {} diff --git a/axum-macros/tests/debug_handler/pass/self_receiver.rs b/axum-macros/tests/debug_handler/pass/self_receiver.rs index e7bf81ce6c..9b72284502 100644 --- a/axum-macros/tests/debug_handler/pass/self_receiver.rs +++ b/axum-macros/tests/debug_handler/pass/self_receiver.rs @@ -1,34 +1,31 @@ use axum::{ async_trait, - extract::FromRequest, - http::Request, + extract::{Request, FromRequest}, }; use axum_macros::debug_handler; struct A; #[async_trait] -impl FromRequest for A +impl FromRequest for A where - B: Send + 'static, S: Send + Sync, { type Rejection = (); - async fn from_request(_req: Request, _state: &S) -> Result { + async fn from_request(_req: Request, _state: &S) -> Result { unimplemented!() } } #[async_trait] -impl FromRequest for Box +impl FromRequest for Box where - B: Send + 'static, S: Send + Sync, { type Rejection = (); - async fn from_request(_req: Request, _state: &S) -> Result { + async fn from_request(_req: Request, _state: &S) -> Result { unimplemented!() } } diff --git a/axum-macros/tests/debug_handler/pass/set_state.rs b/axum-macros/tests/debug_handler/pass/set_state.rs index 5c84dbd25b..60a7a3304e 100644 --- a/axum-macros/tests/debug_handler/pass/set_state.rs +++ b/axum-macros/tests/debug_handler/pass/set_state.rs @@ -1,7 +1,6 @@ use axum_macros::debug_handler; -use axum::extract::{FromRef, FromRequest}; +use axum::extract::{Request, FromRef, FromRequest}; use axum::async_trait; -use axum::http::Request; #[debug_handler(state = AppState)] async fn handler(_: A) {} @@ -12,15 +11,14 @@ struct AppState; struct A; #[async_trait] -impl FromRequest for A +impl FromRequest for A where - B: Send + 'static, S: Send + Sync, AppState: FromRef, { type Rejection = (); - async fn from_request(_req: Request, _state: &S) -> Result { + async fn from_request(_req: Request, _state: &S) -> Result { unimplemented!() } } diff --git a/axum-macros/tests/debug_handler/pass/state_and_body.rs b/axum-macros/tests/debug_handler/pass/state_and_body.rs index 7e1525f524..f348360b3a 100644 --- a/axum-macros/tests/debug_handler/pass/state_and_body.rs +++ b/axum-macros/tests/debug_handler/pass/state_and_body.rs @@ -1,8 +1,8 @@ use axum_macros::debug_handler; -use axum::{body::BoxBody, extract::State, http::Request}; +use axum::{extract::State, extract::Request}; -#[debug_handler(state = AppState, body = BoxBody)] -async fn handler(_: State, _: Request) {} +#[debug_handler(state = AppState)] +async fn handler(_: State, _: Request) {} #[derive(Clone)] struct AppState; diff --git a/axum-macros/tests/from_request/fail/generic_without_via.rs b/axum-macros/tests/from_request/fail/generic_without_via.rs index 38eaa437a3..f0d54acfa9 100644 --- a/axum-macros/tests/from_request/fail/generic_without_via.rs +++ b/axum-macros/tests/from_request/fail/generic_without_via.rs @@ -1,4 +1,4 @@ -use axum::{body::Body, routing::get, Router}; +use axum::{routing::get, Router}; use axum_macros::FromRequest; #[derive(FromRequest, Clone)] @@ -7,5 +7,5 @@ struct Extractor(T); async fn foo(_: Extractor<()>) {} fn main() { - Router::<(), Body>::new().route("/", get(foo)); + _ = Router::<()>::new().route("/", get(foo)); } diff --git a/axum-macros/tests/from_request/fail/generic_without_via.stderr b/axum-macros/tests/from_request/fail/generic_without_via.stderr index 7630c9bf75..961d6a5b35 100644 --- a/axum-macros/tests/from_request/fail/generic_without_via.stderr +++ b/axum-macros/tests/from_request/fail/generic_without_via.stderr @@ -4,21 +4,21 @@ error: #[derive(FromRequest)] only supports generics when used with #[from_reque 5 | struct Extractor(T); | ^ -error[E0277]: the trait bound `fn(Extractor<()>) -> impl Future {foo}: Handler<_, _, _>` is not satisfied - --> tests/from_request/fail/generic_without_via.rs:10:46 - | -10 | Router::<(), Body>::new().route("/", get(foo)); - | --- ^^^ the trait `Handler<_, _, _>` is not implemented for fn item `fn(Extractor<()>) -> impl Future {foo}` - | | - | required by a bound introduced by this call - | - = note: Consider using `#[axum::debug_handler]` to improve the error message - = help: the following other types implement trait `Handler`: - as Handler> - as Handler<(), S, B>> +error[E0277]: the trait bound `fn(Extractor<()>) -> impl Future {foo}: Handler<_, _>` is not satisfied + --> tests/from_request/fail/generic_without_via.rs:10:44 + | +10 | _ = Router::<()>::new().route("/", get(foo)); + | --- ^^^ the trait `Handler<_, _>` is not implemented for fn item `fn(Extractor<()>) -> impl Future {foo}` + | | + | required by a bound introduced by this call + | + = note: Consider using `#[axum::debug_handler]` to improve the error message + = help: the following other types implement trait `Handler`: + as Handler> + as Handler<(), S>> note: required by a bound in `axum::routing::get` - --> $WORKSPACE/axum/src/routing/method_routing.rs - | - | top_level_handler_fn!(get, GET); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `axum::routing::get` - = note: this error originates in the macro `top_level_handler_fn` (in Nightly builds, run with -Z macro-backtrace for more info) + --> $WORKSPACE/axum/src/routing/method_routing.rs + | + | top_level_handler_fn!(get, GET); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `get` + = note: this error originates in the macro `top_level_handler_fn` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/axum-macros/tests/from_request/fail/generic_without_via_rejection.rs b/axum-macros/tests/from_request/fail/generic_without_via_rejection.rs index 38d6b0910b..b1ce072cb4 100644 --- a/axum-macros/tests/from_request/fail/generic_without_via_rejection.rs +++ b/axum-macros/tests/from_request/fail/generic_without_via_rejection.rs @@ -1,4 +1,4 @@ -use axum::{body::Body, routing::get, Router}; +use axum::{routing::get, Router}; use axum_macros::FromRequest; #[derive(FromRequest, Clone)] @@ -8,5 +8,5 @@ struct Extractor(T); async fn foo(_: Extractor<()>) {} fn main() { - Router::<(), Body>::new().route("/", get(foo)); + _ = Router::<()>::new().route("/", get(foo)); } diff --git a/axum-macros/tests/from_request/fail/generic_without_via_rejection.stderr b/axum-macros/tests/from_request/fail/generic_without_via_rejection.stderr index 65f0e64d74..00eb8d09aa 100644 --- a/axum-macros/tests/from_request/fail/generic_without_via_rejection.stderr +++ b/axum-macros/tests/from_request/fail/generic_without_via_rejection.stderr @@ -4,21 +4,21 @@ error: #[derive(FromRequest)] only supports generics when used with #[from_reque 6 | struct Extractor(T); | ^ -error[E0277]: the trait bound `fn(Extractor<()>) -> impl Future {foo}: Handler<_, _, _>` is not satisfied - --> tests/from_request/fail/generic_without_via_rejection.rs:11:46 - | -11 | Router::<(), Body>::new().route("/", get(foo)); - | --- ^^^ the trait `Handler<_, _, _>` is not implemented for fn item `fn(Extractor<()>) -> impl Future {foo}` - | | - | required by a bound introduced by this call - | - = note: Consider using `#[axum::debug_handler]` to improve the error message - = help: the following other types implement trait `Handler`: - as Handler> - as Handler<(), S, B>> +error[E0277]: the trait bound `fn(Extractor<()>) -> impl Future {foo}: Handler<_, _>` is not satisfied + --> tests/from_request/fail/generic_without_via_rejection.rs:11:44 + | +11 | _ = Router::<()>::new().route("/", get(foo)); + | --- ^^^ the trait `Handler<_, _>` is not implemented for fn item `fn(Extractor<()>) -> impl Future {foo}` + | | + | required by a bound introduced by this call + | + = note: Consider using `#[axum::debug_handler]` to improve the error message + = help: the following other types implement trait `Handler`: + as Handler> + as Handler<(), S>> note: required by a bound in `axum::routing::get` - --> $WORKSPACE/axum/src/routing/method_routing.rs - | - | top_level_handler_fn!(get, GET); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `axum::routing::get` - = note: this error originates in the macro `top_level_handler_fn` (in Nightly builds, run with -Z macro-backtrace for more info) + --> $WORKSPACE/axum/src/routing/method_routing.rs + | + | top_level_handler_fn!(get, GET); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `get` + = note: this error originates in the macro `top_level_handler_fn` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/axum-macros/tests/from_request/fail/override_rejection_on_enum_without_via.stderr b/axum-macros/tests/from_request/fail/override_rejection_on_enum_without_via.stderr index d5a11d81d0..ca8353b2b7 100644 --- a/axum-macros/tests/from_request/fail/override_rejection_on_enum_without_via.stderr +++ b/axum-macros/tests/from_request/fail/override_rejection_on_enum_without_via.stderr @@ -4,40 +4,40 @@ error: cannot use `rejection` without `via` 18 | #[from_request(rejection(MyRejection))] | ^^^^^^^^^ -error[E0277]: the trait bound `fn(MyExtractor) -> impl Future {handler}: Handler<_, _, _>` is not satisfied - --> tests/from_request/fail/override_rejection_on_enum_without_via.rs:10:50 - | -10 | let _: Router = Router::new().route("/", get(handler).post(handler_result)); - | --- ^^^^^^^ the trait `Handler<_, _, _>` is not implemented for fn item `fn(MyExtractor) -> impl Future {handler}` - | | - | required by a bound introduced by this call - | - = note: Consider using `#[axum::debug_handler]` to improve the error message - = help: the following other types implement trait `Handler`: - as Handler> - as Handler<(), S, B>> +error[E0277]: the trait bound `fn(MyExtractor) -> impl Future {handler}: Handler<_, _>` is not satisfied + --> tests/from_request/fail/override_rejection_on_enum_without_via.rs:10:50 + | +10 | let _: Router = Router::new().route("/", get(handler).post(handler_result)); + | --- ^^^^^^^ the trait `Handler<_, _>` is not implemented for fn item `fn(MyExtractor) -> impl Future {handler}` + | | + | required by a bound introduced by this call + | + = note: Consider using `#[axum::debug_handler]` to improve the error message + = help: the following other types implement trait `Handler`: + as Handler> + as Handler<(), S>> note: required by a bound in `axum::routing::get` - --> $WORKSPACE/axum/src/routing/method_routing.rs - | - | top_level_handler_fn!(get, GET); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `axum::routing::get` - = note: this error originates in the macro `top_level_handler_fn` (in Nightly builds, run with -Z macro-backtrace for more info) + --> $WORKSPACE/axum/src/routing/method_routing.rs + | + | top_level_handler_fn!(get, GET); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `get` + = note: this error originates in the macro `top_level_handler_fn` (in Nightly builds, run with -Z macro-backtrace for more info) -error[E0277]: the trait bound `fn(Result) -> impl Future {handler_result}: Handler<_, _, _>` is not satisfied - --> tests/from_request/fail/override_rejection_on_enum_without_via.rs:10:64 - | -10 | let _: Router = Router::new().route("/", get(handler).post(handler_result)); - | ---- ^^^^^^^^^^^^^^ the trait `Handler<_, _, _>` is not implemented for fn item `fn(Result) -> impl Future {handler_result}` - | | - | required by a bound introduced by this call - | - = note: Consider using `#[axum::debug_handler]` to improve the error message - = help: the following other types implement trait `Handler`: - as Handler> - as Handler<(), S, B>> -note: required by a bound in `MethodRouter::::post` - --> $WORKSPACE/axum/src/routing/method_routing.rs - | - | chained_handler_fn!(post, POST); - | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `MethodRouter::::post` - = note: this error originates in the macro `chained_handler_fn` (in Nightly builds, run with -Z macro-backtrace for more info) +error[E0277]: the trait bound `fn(Result) -> impl Future {handler_result}: Handler<_, _>` is not satisfied + --> tests/from_request/fail/override_rejection_on_enum_without_via.rs:10:64 + | +10 | let _: Router = Router::new().route("/", get(handler).post(handler_result)); + | ---- ^^^^^^^^^^^^^^ the trait `Handler<_, _>` is not implemented for fn item `fn(Result) -> impl Future {handler_result}` + | | + | required by a bound introduced by this call + | + = note: Consider using `#[axum::debug_handler]` to improve the error message + = help: the following other types implement trait `Handler`: + as Handler> + as Handler<(), S>> +note: required by a bound in `MethodRouter::::post` + --> $WORKSPACE/axum/src/routing/method_routing.rs + | + | chained_handler_fn!(post, POST); + | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ required by this bound in `MethodRouter::::post` + = note: this error originates in the macro `chained_handler_fn` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/axum-macros/tests/from_request/fail/parts_extracting_body.stderr b/axum-macros/tests/from_request/fail/parts_extracting_body.stderr index 54c0dc0222..896cf2d991 100644 --- a/axum-macros/tests/from_request/fail/parts_extracting_body.stderr +++ b/axum-macros/tests/from_request/fail/parts_extracting_body.stderr @@ -15,4 +15,4 @@ error[E0277]: the trait bound `String: FromRequestParts` is not satisfied <(T1, T2, T3, T4, T5, T6) as FromRequestParts> <(T1, T2, T3, T4, T5, T6, T7) as FromRequestParts> <(T1, T2, T3, T4, T5, T6, T7, T8) as FromRequestParts> - and 27 others + and $N others diff --git a/axum-macros/tests/from_request/fail/state_infer_multiple_different_types.rs b/axum-macros/tests/from_request/fail/state_infer_multiple_different_types.rs index 57400377ef..6533d3276a 100644 --- a/axum-macros/tests/from_request/fail/state_infer_multiple_different_types.rs +++ b/axum-macros/tests/from_request/fail/state_infer_multiple_different_types.rs @@ -15,7 +15,7 @@ struct OtherState {} fn assert_from_request() where - Extractor: axum::extract::FromRequest, + Extractor: axum::extract::FromRequest, { } diff --git a/axum-macros/tests/from_request/pass/container.rs b/axum-macros/tests/from_request/pass/container.rs index 6e62c569a4..9d4e0666e9 100644 --- a/axum-macros/tests/from_request/pass/container.rs +++ b/axum-macros/tests/from_request/pass/container.rs @@ -1,5 +1,4 @@ use axum::{ - body::Body, extract::{FromRequest, Json}, response::Response, }; @@ -15,7 +14,7 @@ struct Extractor { fn assert_from_request() where - Extractor: FromRequest<(), Body, Rejection = Response>, + Extractor: FromRequest<(), Rejection = Response>, { } diff --git a/axum-macros/tests/from_request/pass/empty_named.rs b/axum-macros/tests/from_request/pass/empty_named.rs index eec021d0f5..63af28f5d0 100644 --- a/axum-macros/tests/from_request/pass/empty_named.rs +++ b/axum-macros/tests/from_request/pass/empty_named.rs @@ -5,7 +5,7 @@ struct Extractor {} fn assert_from_request() where - Extractor: axum::extract::FromRequest<(), axum::body::Body, Rejection = std::convert::Infallible>, + Extractor: axum::extract::FromRequest<(), Rejection = std::convert::Infallible>, { } diff --git a/axum-macros/tests/from_request/pass/empty_tuple.rs b/axum-macros/tests/from_request/pass/empty_tuple.rs index 3d8bcd25c0..b740cb8374 100644 --- a/axum-macros/tests/from_request/pass/empty_tuple.rs +++ b/axum-macros/tests/from_request/pass/empty_tuple.rs @@ -5,7 +5,7 @@ struct Extractor(); fn assert_from_request() where - Extractor: axum::extract::FromRequest<(), axum::body::Body, Rejection = std::convert::Infallible>, + Extractor: axum::extract::FromRequest<(), Rejection = std::convert::Infallible>, { } diff --git a/axum-macros/tests/from_request/pass/enum_via.rs b/axum-macros/tests/from_request/pass/enum_via.rs index c68b9796a7..17c6ba80f3 100644 --- a/axum-macros/tests/from_request/pass/enum_via.rs +++ b/axum-macros/tests/from_request/pass/enum_via.rs @@ -1,4 +1,4 @@ -use axum::{body::Body, routing::get, Extension, Router}; +use axum::{routing::get, Extension, Router}; use axum_macros::FromRequest; #[derive(FromRequest, Clone)] @@ -8,5 +8,5 @@ enum Extractor {} async fn foo(_: Extractor) {} fn main() { - Router::<(), Body>::new().route("/", get(foo)); + _ = Router::<()>::new().route("/", get(foo)); } diff --git a/axum-macros/tests/from_request/pass/enum_via_parts.rs b/axum-macros/tests/from_request/pass/enum_via_parts.rs index 5e18d9228d..049598c339 100644 --- a/axum-macros/tests/from_request/pass/enum_via_parts.rs +++ b/axum-macros/tests/from_request/pass/enum_via_parts.rs @@ -1,4 +1,4 @@ -use axum::{body::Body, routing::get, Extension, Router}; +use axum::{routing::get, Extension, Router}; use axum_macros::FromRequestParts; #[derive(FromRequestParts, Clone)] @@ -8,5 +8,5 @@ enum Extractor {} async fn foo(_: Extractor) {} fn main() { - Router::<(), Body>::new().route("/", get(foo)); + _ = Router::<()>::new().route("/", get(foo)); } diff --git a/axum-macros/tests/from_request/pass/named.rs b/axum-macros/tests/from_request/pass/named.rs index e042477b90..f63ae8e9db 100644 --- a/axum-macros/tests/from_request/pass/named.rs +++ b/axum-macros/tests/from_request/pass/named.rs @@ -1,7 +1,10 @@ use axum::{ - body::Body, - extract::{FromRequest, TypedHeader, rejection::TypedHeaderRejection}, + extract::FromRequest, response::Response, +}; +use axum_extra::{ + TypedHeader, + typed_header::TypedHeaderRejection, headers::{self, UserAgent}, }; @@ -17,7 +20,7 @@ struct Extractor { fn assert_from_request() where - Extractor: FromRequest<(), Body, Rejection = Response>, + Extractor: FromRequest<(), Rejection = Response>, { } diff --git a/axum-macros/tests/from_request/pass/named_parts.rs b/axum-macros/tests/from_request/pass/named_parts.rs index 27dce64f21..cbb67e61da 100644 --- a/axum-macros/tests/from_request/pass/named_parts.rs +++ b/axum-macros/tests/from_request/pass/named_parts.rs @@ -1,8 +1,12 @@ use axum::{ - extract::{rejection::TypedHeaderRejection, FromRequestParts, TypedHeader}, - headers::{self, UserAgent}, + extract::FromRequestParts, response::Response, }; +use axum_extra::{ + TypedHeader, + typed_header::TypedHeaderRejection, + headers::{self, UserAgent}, +}; #[derive(FromRequestParts)] struct Extractor { diff --git a/axum-macros/tests/from_request/pass/named_via.rs b/axum-macros/tests/from_request/pass/named_via.rs index 41cc361556..691627b08d 100644 --- a/axum-macros/tests/from_request/pass/named_via.rs +++ b/axum-macros/tests/from_request/pass/named_via.rs @@ -1,10 +1,10 @@ use axum::{ - body::Body, response::Response, - extract::{ - rejection::TypedHeaderRejection, - Extension, FromRequest, TypedHeader, - }, + extract::{Extension, FromRequest}, +}; +use axum_extra::{ + TypedHeader, + typed_header::TypedHeaderRejection, headers::{self, UserAgent}, }; @@ -24,7 +24,7 @@ struct Extractor { fn assert_from_request() where - Extractor: FromRequest<(), Body, Rejection = Response>, + Extractor: FromRequest<(), Rejection = Response>, { } diff --git a/axum-macros/tests/from_request/pass/named_via_parts.rs b/axum-macros/tests/from_request/pass/named_via_parts.rs index 9a389e549b..0377af7b10 100644 --- a/axum-macros/tests/from_request/pass/named_via_parts.rs +++ b/axum-macros/tests/from_request/pass/named_via_parts.rs @@ -1,9 +1,10 @@ use axum::{ response::Response, - extract::{ - rejection::TypedHeaderRejection, - Extension, FromRequestParts, TypedHeader, - }, + extract::{Extension, FromRequestParts}, +}; +use axum_extra::{ + TypedHeader, + typed_header::TypedHeaderRejection, headers::{self, UserAgent}, }; diff --git a/axum-macros/tests/from_request/pass/override_rejection.rs b/axum-macros/tests/from_request/pass/override_rejection.rs index 0147c9a8b3..25e399b4e0 100644 --- a/axum-macros/tests/from_request/pass/override_rejection.rs +++ b/axum-macros/tests/from_request/pass/override_rejection.rs @@ -1,7 +1,7 @@ use axum::{ async_trait, - extract::{rejection::ExtensionRejection, FromRequest}, - http::{StatusCode, Request}, + extract::{Request, rejection::ExtensionRejection, FromRequest}, + http::StatusCode, response::{IntoResponse, Response}, routing::get, Extension, Router, @@ -27,15 +27,14 @@ struct MyExtractor { struct OtherExtractor; #[async_trait] -impl FromRequest for OtherExtractor +impl FromRequest for OtherExtractor where - B: Send + 'static, S: Send + Sync, { // this rejection doesn't implement `Display` and `Error` type Rejection = (StatusCode, String); - async fn from_request(_req: Request, _state: &S) -> Result { + async fn from_request(_req: Request, _state: &S) -> Result { todo!() } } diff --git a/axum-macros/tests/from_request/pass/state_cookie.rs b/axum-macros/tests/from_request/pass/state_cookie.rs index a4f46c6acd..6e2aa1f4ed 100644 --- a/axum-macros/tests/from_request/pass/state_cookie.rs +++ b/axum-macros/tests/from_request/pass/state_cookie.rs @@ -20,7 +20,7 @@ impl FromRef for Key { fn assert_from_request() where - Extractor: axum::extract::FromRequest, + Extractor: axum::extract::FromRequest, { } diff --git a/axum-macros/tests/from_request/pass/state_infer.rs b/axum-macros/tests/from_request/pass/state_infer.rs index 5290614991..07545ab074 100644 --- a/axum-macros/tests/from_request/pass/state_infer.rs +++ b/axum-macros/tests/from_request/pass/state_infer.rs @@ -11,7 +11,7 @@ struct AppState {} fn assert_from_request() where - Extractor: axum::extract::FromRequest, + Extractor: axum::extract::FromRequest, { } diff --git a/axum-macros/tests/from_request/pass/state_infer_multiple.rs b/axum-macros/tests/from_request/pass/state_infer_multiple.rs index 6729e61572..cb8de1d59c 100644 --- a/axum-macros/tests/from_request/pass/state_infer_multiple.rs +++ b/axum-macros/tests/from_request/pass/state_infer_multiple.rs @@ -12,7 +12,7 @@ struct AppState {} fn assert_from_request() where - Extractor: axum::extract::FromRequest, + Extractor: axum::extract::FromRequest, { } diff --git a/axum-macros/tests/from_request/pass/tuple.rs b/axum-macros/tests/from_request/pass/tuple.rs index 2af407d0f9..85a409817e 100644 --- a/axum-macros/tests/from_request/pass/tuple.rs +++ b/axum-macros/tests/from_request/pass/tuple.rs @@ -5,7 +5,7 @@ struct Extractor(axum::http::HeaderMap, String); fn assert_from_request() where - Extractor: axum::extract::FromRequest<(), axum::body::Body>, + Extractor: axum::extract::FromRequest<()>, { } diff --git a/axum-macros/tests/from_request/pass/tuple_same_type_twice.rs b/axum-macros/tests/from_request/pass/tuple_same_type_twice.rs index 227e4a3c8f..343563ddb6 100644 --- a/axum-macros/tests/from_request/pass/tuple_same_type_twice.rs +++ b/axum-macros/tests/from_request/pass/tuple_same_type_twice.rs @@ -13,7 +13,7 @@ struct Payload {} fn assert_from_request() where - Extractor: axum::extract::FromRequest<(), axum::body::Body>, + Extractor: axum::extract::FromRequest<()>, { } diff --git a/axum-macros/tests/from_request/pass/tuple_same_type_twice_via.rs b/axum-macros/tests/from_request/pass/tuple_same_type_twice_via.rs index 82342c56c5..ab0ee467f6 100644 --- a/axum-macros/tests/from_request/pass/tuple_same_type_twice_via.rs +++ b/axum-macros/tests/from_request/pass/tuple_same_type_twice_via.rs @@ -14,7 +14,7 @@ struct Payload {} fn assert_from_request() where - Extractor: axum::extract::FromRequest<(), axum::body::Body, Rejection = Response>, + Extractor: axum::extract::FromRequest<(), Rejection = Response>, { } diff --git a/axum-macros/tests/from_request/pass/tuple_via.rs b/axum-macros/tests/from_request/pass/tuple_via.rs index 03a9e3610c..3b62287ed8 100644 --- a/axum-macros/tests/from_request/pass/tuple_via.rs +++ b/axum-macros/tests/from_request/pass/tuple_via.rs @@ -9,7 +9,7 @@ struct State; fn assert_from_request() where - Extractor: axum::extract::FromRequest<(), axum::body::Body>, + Extractor: axum::extract::FromRequest<()>, { } diff --git a/axum-macros/tests/from_request/pass/unit.rs b/axum-macros/tests/from_request/pass/unit.rs index 3e5d986917..9a4dc1dd44 100644 --- a/axum-macros/tests/from_request/pass/unit.rs +++ b/axum-macros/tests/from_request/pass/unit.rs @@ -5,7 +5,7 @@ struct Extractor; fn assert_from_request() where - Extractor: axum::extract::FromRequest<(), axum::body::Body, Rejection = std::convert::Infallible>, + Extractor: axum::extract::FromRequest<(), Rejection = std::convert::Infallible>, { } diff --git a/axum-macros/tests/typed_path/pass/customize_rejection.rs b/axum-macros/tests/typed_path/pass/customize_rejection.rs index 40f3ec0ada..01f11fc94c 100644 --- a/axum-macros/tests/typed_path/pass/customize_rejection.rs +++ b/axum-macros/tests/typed_path/pass/customize_rejection.rs @@ -40,7 +40,7 @@ impl Default for MyRejection { } fn main() { - axum::Router::<(), axum::body::Body>::new() + _ = axum::Router::<()>::new() .typed_get(|_: Result| async {}) .typed_post(|_: Result| async {}) .typed_put(|_: Result| async {}); diff --git a/axum-macros/tests/typed_path/pass/named_fields_struct.rs b/axum-macros/tests/typed_path/pass/named_fields_struct.rs index 6119304080..042936fe02 100644 --- a/axum-macros/tests/typed_path/pass/named_fields_struct.rs +++ b/axum-macros/tests/typed_path/pass/named_fields_struct.rs @@ -9,7 +9,7 @@ struct MyPath { } fn main() { - axum::Router::<(), axum::body::Body>::new().route("/", axum::routing::get(|_: MyPath| async {})); + _ = axum::Router::<()>::new().route("/", axum::routing::get(|_: MyPath| async {})); assert_eq!(MyPath::PATH, "/users/:user_id/teams/:team_id"); assert_eq!( diff --git a/axum-macros/tests/typed_path/pass/option_result.rs b/axum-macros/tests/typed_path/pass/option_result.rs index bd4c6dc282..1bd2359010 100644 --- a/axum-macros/tests/typed_path/pass/option_result.rs +++ b/axum-macros/tests/typed_path/pass/option_result.rs @@ -19,7 +19,7 @@ struct UsersIndex; async fn result_handler_unit_struct(_: Result) {} fn main() { - axum::Router::<(), axum::body::Body>::new() + _ = axum::Router::<()>::new() .typed_get(option_handler) .typed_post(result_handler) .typed_post(result_handler_unit_struct); diff --git a/axum-macros/tests/typed_path/pass/tuple_struct.rs b/axum-macros/tests/typed_path/pass/tuple_struct.rs index 4f8fa17eeb..3ee8370402 100644 --- a/axum-macros/tests/typed_path/pass/tuple_struct.rs +++ b/axum-macros/tests/typed_path/pass/tuple_struct.rs @@ -8,7 +8,7 @@ pub type Result = std::result::Result; struct MyPath(u32, u32); fn main() { - axum::Router::<(), axum::body::Body>::new().route("/", axum::routing::get(|_: MyPath| async {})); + _ = axum::Router::<()>::new().route("/", axum::routing::get(|_: MyPath| async {})); assert_eq!(MyPath::PATH, "/users/:user_id/teams/:team_id"); assert_eq!(format!("{}", MyPath(1, 2)), "/users/1/teams/2"); diff --git a/axum-macros/tests/typed_path/pass/unit_struct.rs b/axum-macros/tests/typed_path/pass/unit_struct.rs index 0ba27f81ac..f3bb164075 100644 --- a/axum-macros/tests/typed_path/pass/unit_struct.rs +++ b/axum-macros/tests/typed_path/pass/unit_struct.rs @@ -5,7 +5,7 @@ use axum_extra::routing::TypedPath; struct MyPath; fn main() { - axum::Router::<(), axum::body::Body>::new() + _ = axum::Router::<()>::new() .route("/", axum::routing::get(|_: MyPath| async {})); assert_eq!(MyPath::PATH, "/users"); diff --git a/axum-macros/tests/typed_path/pass/wildcards.rs b/axum-macros/tests/typed_path/pass/wildcards.rs index e7794fc895..98aa5f5153 100644 --- a/axum-macros/tests/typed_path/pass/wildcards.rs +++ b/axum-macros/tests/typed_path/pass/wildcards.rs @@ -8,5 +8,5 @@ struct MyPath { } fn main() { - axum::Router::<(), axum::body::Body>::new().typed_get(|_: MyPath| async {}); + _ = axum::Router::<()>::new().typed_get(|_: MyPath| async {}); } diff --git a/axum/CHANGELOG.md b/axum/CHANGELOG.md index c0f92e36d5..9bb555bbdf 100644 --- a/axum/CHANGELOG.md +++ b/axum/CHANGELOG.md @@ -7,7 +7,57 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 # Unreleased -- None. +- **breaking:** The following types/traits are no longer generic over the request body + (i.e. the `B` type param has been removed) ([#1751] and [#1789]): + - `FromRequestParts` + - `FromRequest` + - `HandlerService` + - `HandlerWithoutStateExt` + - `Handler` + - `LayeredFuture` + - `Layered` + - `MethodRouter` + - `Next` + - `RequestExt` + - `RouteFuture` + - `Route` + - `Router` +- **breaking:** axum no longer re-exports `hyper::Body` as that type is removed + in hyper 1.0. Instead axum has its own body type at `axum::body::Body` ([#1751]) +- **breaking:** `extract::BodyStream` has been removed as `body::Body` + implements `Stream` and `FromRequest` directly ([#1751]) +- **breaking:** Change `sse::Event::json_data` to use `axum_core::Error` as its error type ([#1762]) +- **breaking:** Rename `DefaultOnFailedUpdgrade` to `DefaultOnFailedUpgrade` ([#1664]) +- **breaking:** Rename `OnFailedUpdgrade` to `OnFailedUpgrade` ([#1664]) +- **breaking:** `TypedHeader` has been move to `axum-extra` ([#1850]) +- **breaking:** Removed re-exports of `Empty` and `Full`. Use + `axum::body::Body::empty` and `axum::body::Body::from` respectively ([#1789]) +- **breaking:** The response returned by `IntoResponse::into_response` must use + `axum::body::Body` as the body type. `axum::response::Response` does this + ([#1789]) +- **breaking:** Removed the `BoxBody` type alias and its `box_body` + constructor. Use `axum::body::Body::new` instead ([#1789]) +- **breaking:** Remove `RawBody` extractor. `axum::body::Body` implements `FromRequest` directly ([#1789]) +- **breaking:** The following types from `http-body` no longer implement `IntoResponse`: + - `Full`, use `Body::from` instead + - `Empty`, use `Body::empty` instead + - `BoxBody`, use `Body::new` instead + - `UnsyncBoxBody`, use `Body::new` instead + - `MapData`, use `Body::new` instead + - `MapErr`, use `Body::new` instead +- **added:** Add `axum::extract::Request` type alias where the body is `axum::body::Body` ([#1789]) +- **added:** Add `Router::as_service` and `Router::into_service` to workaround + type inference issues when calling `ServiceExt` methods on a `Router` ([#1835]) +- **breaking:** Removed `axum::Server` as it was removed in hyper 1.0. Instead + use `axum::serve(listener, service)` or hyper/hyper-util for more configuration options ([#1868]) + +[#1664]: https://github.com/tokio-rs/axum/pull/1664 +[#1751]: https://github.com/tokio-rs/axum/pull/1751 +[#1762]: https://github.com/tokio-rs/axum/pull/1762 +[#1789]: https://github.com/tokio-rs/axum/pull/1789 +[#1835]: https://github.com/tokio-rs/axum/pull/1835 +[#1850]: https://github.com/tokio-rs/axum/pull/1850 +[#1868]: https://github.com/tokio-rs/axum/pull/1868 # 0.6.16 (18. April, 2023) diff --git a/axum/Cargo.toml b/axum/Cargo.toml index 5f82592b6a..6897e4e447 100644 --- a/axum/Cargo.toml +++ b/axum/Cargo.toml @@ -51,10 +51,13 @@ tower = { version = "0.4.13", default-features = false, features = ["util"] } tower-layer = "0.3.2" tower-service = "0.3" +# wont need this when axum uses http-body 1.0 +hyper1 = { package = "hyper", version = "1.0.0-rc.3", features = ["server", "http1"] } +tower-hyper-http-body-compat = { version = "0.1.4", features = ["server", "http1"] } + # optional dependencies axum-macros = { path = "../axum-macros", version = "0.3.7", optional = true } base64 = { version = "0.21.0", optional = true } -headers = { version = "0.3.7", optional = true } multer = { version = "2.0.0", optional = true } serde_json = { version = "1.0", features = ["raw_value"], optional = true } serde_path_to_error = { version = "0.1.8", optional = true } @@ -186,13 +189,11 @@ allowed = [ "futures_core", "futures_sink", "futures_util", - "headers", - "headers_core", "http", "http_body", "hyper", "serde", - "serde_json", + "tokio", "tower_layer", "tower_service", ] diff --git a/axum/README.md b/axum/README.md index 08487807c5..264ba56dd5 100644 --- a/axum/README.md +++ b/axum/README.md @@ -48,13 +48,8 @@ async fn main() { .route("/users", post(create_user)); // run our app with hyper - // `axum::Server` is a re-export of `hyper::Server` - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) - .await - .unwrap(); + let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); + axum::serve(listener, app).await.unwrap(); } // basic handler that responds with a static string diff --git a/axum/benches/benches.rs b/axum/benches/benches.rs index c3b9c19e34..4fad5e3d64 100644 --- a/axum/benches/benches.rs +++ b/axum/benches/benches.rs @@ -1,7 +1,7 @@ use axum::{ extract::State, routing::{get, post}, - Extension, Json, Router, Server, + Extension, Json, Router, }; use hyper::server::conn::AddrIncoming; use serde::{Deserialize, Serialize}; @@ -164,7 +164,7 @@ impl BenchmarkBuilder { std::thread::spawn(move || { rt.block_on(async move { let incoming = AddrIncoming::from_listener(listener).unwrap(); - Server::builder(incoming) + hyper::Server::builder(incoming) .serve(app.into_make_service()) .await .unwrap(); diff --git a/axum/src/body/mod.rs b/axum/src/body/mod.rs index 4eceec0ced..0e3d478179 100644 --- a/axum/src/body/mod.rs +++ b/axum/src/body/mod.rs @@ -1,17 +1,10 @@ //! HTTP body utilities. -mod stream_body; - -pub use self::stream_body::StreamBody; - -#[doc(no_inline)] -pub use http_body::{Body as HttpBody, Empty, Full}; - #[doc(no_inline)] -pub use hyper::body::Body; +pub use http_body::Body as HttpBody; #[doc(no_inline)] pub use bytes::Bytes; #[doc(inline)] -pub use axum_core::body::{boxed, BoxBody}; +pub use axum_core::body::Body; diff --git a/axum/src/body/stream_body.rs b/axum/src/body/stream_body.rs index 1c2955eaa9..933d10511d 100644 --- a/axum/src/body/stream_body.rs +++ b/axum/src/body/stream_body.rs @@ -1,8 +1,9 @@ use crate::{ - body::{self, Bytes, HttpBody}, + body::{Bytes, HttpBody}, response::{IntoResponse, Response}, BoxError, Error, }; +use axum_core::body::Body; use futures_util::{ ready, stream::{self, TryStream}, @@ -21,7 +22,7 @@ pin_project! { /// /// The purpose of this type is to be used in responses. If you want to /// extract the request body as a stream consider using - /// [`BodyStream`](crate::extract::BodyStream). + /// [`Body`](crate::body::Body). /// /// # Example /// @@ -46,9 +47,7 @@ pin_project! { /// } /// /// let app = Router::new().route("/", get(handler)); - /// # async { - /// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); - /// # }; + /// # let _: Router = app; /// ``` /// /// [`Stream`]: futures_util::stream::Stream @@ -93,7 +92,7 @@ where S::Error: Into, { fn into_response(self) -> Response { - Response::new(body::boxed(self)) + Response::new(Body::new(self)) } } diff --git a/axum/src/boxed.rs b/axum/src/boxed.rs index f8191f2e26..5473b2491b 100644 --- a/axum/src/boxed.rs +++ b/axum/src/boxed.rs @@ -1,27 +1,24 @@ use std::{convert::Infallible, fmt}; -use http::Request; +use crate::extract::Request; use tower::Service; use crate::{ - body::HttpBody, handler::Handler, routing::{future::RouteFuture, Route}, Router, }; -pub(crate) struct BoxedIntoRoute(Box>); +pub(crate) struct BoxedIntoRoute(Box>); -impl BoxedIntoRoute +impl BoxedIntoRoute where S: Clone + Send + Sync + 'static, - B: Send + 'static, { pub(crate) fn from_handler(handler: H) -> Self where - H: Handler, + H: Handler, T: 'static, - B: HttpBody, { Self(Box::new(MakeErasedHandler { handler, @@ -30,14 +27,12 @@ where } } -impl BoxedIntoRoute { - pub(crate) fn map(self, f: F) -> BoxedIntoRoute +impl BoxedIntoRoute { + pub(crate) fn map(self, f: F) -> BoxedIntoRoute where S: 'static, - B: 'static, E: 'static, - F: FnOnce(Route) -> Route + Clone + Send + 'static, - B2: HttpBody + 'static, + F: FnOnce(Route) -> Route + Clone + Send + 'static, E2: 'static, { BoxedIntoRoute(Box::new(Map { @@ -46,60 +41,55 @@ impl BoxedIntoRoute { })) } - pub(crate) fn into_route(self, state: S) -> Route { + pub(crate) fn into_route(self, state: S) -> Route { self.0.into_route(state) } } -impl Clone for BoxedIntoRoute { +impl Clone for BoxedIntoRoute { fn clone(&self) -> Self { Self(self.0.clone_box()) } } -impl fmt::Debug for BoxedIntoRoute { +impl fmt::Debug for BoxedIntoRoute { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_tuple("BoxedIntoRoute").finish() } } -pub(crate) trait ErasedIntoRoute: Send { - fn clone_box(&self) -> Box>; +pub(crate) trait ErasedIntoRoute: Send { + fn clone_box(&self) -> Box>; - fn into_route(self: Box, state: S) -> Route; + fn into_route(self: Box, state: S) -> Route; - fn call_with_state(self: Box, request: Request, state: S) -> RouteFuture; + fn call_with_state(self: Box, request: Request, state: S) -> RouteFuture; } -pub(crate) struct MakeErasedHandler { +pub(crate) struct MakeErasedHandler { pub(crate) handler: H, - pub(crate) into_route: fn(H, S) -> Route, + pub(crate) into_route: fn(H, S) -> Route, } -impl ErasedIntoRoute for MakeErasedHandler +impl ErasedIntoRoute for MakeErasedHandler where H: Clone + Send + 'static, S: 'static, - B: HttpBody + 'static, { - fn clone_box(&self) -> Box> { + fn clone_box(&self) -> Box> { Box::new(self.clone()) } - fn into_route(self: Box, state: S) -> Route { + fn into_route(self: Box, state: S) -> Route { (self.into_route)(self.handler, state) } - fn call_with_state( - self: Box, - request: Request, - state: S, - ) -> RouteFuture { + fn call_with_state(self: Box, request: Request, state: S) -> RouteFuture { self.into_route(state).call(request) } } -impl Clone for MakeErasedHandler +impl Clone for MakeErasedHandler where H: Clone, { @@ -111,34 +101,29 @@ where } } -pub(crate) struct MakeErasedRouter { - pub(crate) router: Router, - pub(crate) into_route: fn(Router, S) -> Route, +pub(crate) struct MakeErasedRouter { + pub(crate) router: Router, + pub(crate) into_route: fn(Router, S) -> Route, } -impl ErasedIntoRoute for MakeErasedRouter +impl ErasedIntoRoute for MakeErasedRouter where S: Clone + Send + Sync + 'static, - B: HttpBody + Send + 'static, { - fn clone_box(&self) -> Box> { + fn clone_box(&self) -> Box> { Box::new(self.clone()) } - fn into_route(self: Box, state: S) -> Route { + fn into_route(self: Box, state: S) -> Route { (self.into_route)(self.router, state) } - fn call_with_state( - mut self: Box, - request: Request, - state: S, - ) -> RouteFuture { + fn call_with_state(mut self: Box, request: Request, state: S) -> RouteFuture { self.router.call_with_state(request, state) } } -impl Clone for MakeErasedRouter +impl Clone for MakeErasedRouter where S: Clone, { @@ -150,44 +135,42 @@ where } } -pub(crate) struct Map { - pub(crate) inner: Box>, - pub(crate) layer: Box>, +pub(crate) struct Map { + pub(crate) inner: Box>, + pub(crate) layer: Box>, } -impl ErasedIntoRoute for Map +impl ErasedIntoRoute for Map where S: 'static, - B: 'static, E: 'static, - B2: HttpBody + 'static, E2: 'static, { - fn clone_box(&self) -> Box> { + fn clone_box(&self) -> Box> { Box::new(Self { inner: self.inner.clone_box(), layer: self.layer.clone_box(), }) } - fn into_route(self: Box, state: S) -> Route { + fn into_route(self: Box, state: S) -> Route { (self.layer)(self.inner.into_route(state)) } - fn call_with_state(self: Box, request: Request, state: S) -> RouteFuture { + fn call_with_state(self: Box, request: Request, state: S) -> RouteFuture { (self.layer)(self.inner.into_route(state)).call(request) } } -pub(crate) trait LayerFn: FnOnce(Route) -> Route + Send { - fn clone_box(&self) -> Box>; +pub(crate) trait LayerFn: FnOnce(Route) -> Route + Send { + fn clone_box(&self) -> Box>; } -impl LayerFn for F +impl LayerFn for F where - F: FnOnce(Route) -> Route + Clone + Send + 'static, + F: FnOnce(Route) -> Route + Clone + Send + 'static, { - fn clone_box(&self) -> Box> { + fn clone_box(&self) -> Box> { Box::new(self.clone()) } } diff --git a/axum/src/docs/error_handling.md b/axum/src/docs/error_handling.md index 45c768c69a..b9abce6f95 100644 --- a/axum/src/docs/error_handling.md +++ b/axum/src/docs/error_handling.md @@ -85,9 +85,7 @@ async fn handle_anyhow_error(err: anyhow::Error) -> (StatusCode, String) { format!("Something went wrong: {}", err), ) } -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` # Applying fallible middleware @@ -129,9 +127,7 @@ async fn handle_timeout_error(err: BoxError) -> (StatusCode, String) { ) } } -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` # Running extractors for error handling @@ -171,9 +167,7 @@ async fn handle_timeout_error( format!("`{} {}` failed with {}", method, uri, err), ) } -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` [`tower::Service`]: `tower::Service` diff --git a/axum/src/docs/extract.md b/axum/src/docs/extract.md index ed350e5bd8..bba8a0733a 100644 --- a/axum/src/docs/extract.md +++ b/axum/src/docs/extract.md @@ -13,7 +13,6 @@ Types and traits for extracting data from requests. - [Accessing other extractors in `FromRequest` or `FromRequestParts` implementations](#accessing-other-extractors-in-fromrequest-or-fromrequestparts-implementations) - [Request body limits](#request-body-limits) - [Request body extractors](#request-body-extractors) -- [Running extractors from middleware](#running-extractors-from-middleware) - [Wrapping extractors](#wrapping-extractors) - [Logging rejections](#logging-rejections) @@ -47,9 +46,7 @@ async fn create_user(Json(payload): Json) { } let app = Router::new().route("/users", post(create_user)); -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` # Common extractors @@ -58,10 +55,9 @@ Some commonly used extractors are: ```rust,no_run use axum::{ - extract::{Json, TypedHeader, Path, Extension, Query}, + extract::{Request, Json, Path, Extension, Query}, routing::post, - headers::UserAgent, - http::{Request, header::HeaderMap}, + http::header::HeaderMap, body::{Bytes, Body}, Router, }; @@ -78,10 +74,6 @@ async fn query(Query(params): Query>) {} // `HeaderMap` gives you all the headers async fn headers(headers: HeaderMap) {} -// `TypedHeader` can be used to extract a single header -// note this requires you've enabled axum's `headers` feature -async fn user_agent(TypedHeader(user_agent): TypedHeader) {} - // `String` consumes the request body and ensures it is valid utf-8 async fn string(body: String) {} @@ -92,7 +84,7 @@ async fn bytes(body: Bytes) {} async fn json(Json(payload): Json) {} // `Request` gives you the whole request for maximum control -async fn request(request: Request) {} +async fn request(request: Request) {} // `Extension` extracts data from "request extensions" // This is commonly used to share state with handlers @@ -104,16 +96,12 @@ struct State { /* ... */ } let app = Router::new() .route("/path/:user_id", post(path)) .route("/query", post(query)) - .route("/user_agent", post(user_agent)) - .route("/headers", post(headers)) .route("/string", post(string)) .route("/bytes", post(bytes)) .route("/json", post(json)) .route("/request", post(request)) .route("/extension", post(extension)); -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` # Applying multiple extractors @@ -151,9 +139,7 @@ async fn get_user_things( // ... } -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` # The order of extractors @@ -188,7 +174,7 @@ async fn handler( // ... } # -# let _: axum::routing::MethodRouter = axum::routing::get(handler); +# let _: axum::routing::MethodRouter = axum::routing::get(handler); ``` We get a compile error if `String` isn't the last extractor: @@ -253,9 +239,7 @@ async fn create_user(payload: Option>) { } let app = Router::new().route("/users", post(create_user)); -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` Wrapping extractors in `Result` makes them optional and gives you the reason @@ -295,9 +279,7 @@ async fn create_user(payload: Result, JsonRejection>) { } let app = Router::new().route("/users", post(create_user)); -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` # Customizing extractor responses @@ -452,9 +434,7 @@ async fn handler(ExtractUserAgent(user_agent): ExtractUserAgent) { } let app = Router::new().route("/foo", get(handler)); -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` ## Implementing `FromRequest` @@ -464,30 +444,28 @@ If your extractor needs to consume the request body you must implement [`FromReq ```rust,no_run use axum::{ async_trait, - extract::FromRequest, + extract::{Request, FromRequest}, response::{Response, IntoResponse}, - body::Bytes, + body::{Bytes, Body}, routing::get, Router, http::{ StatusCode, header::{HeaderValue, USER_AGENT}, - Request, }, }; struct ValidatedBody(Bytes); #[async_trait] -impl FromRequest for ValidatedBody +impl FromRequest for ValidatedBody where - Bytes: FromRequest, - B: Send + 'static, + Bytes: FromRequest, S: Send + Sync, { type Rejection = Response; - async fn from_request(req: Request, state: &S) -> Result { + async fn from_request(req: Request, state: &S) -> Result { let body = Bytes::from_request(req, state) .await .map_err(IntoResponse::into_response)?; @@ -503,9 +481,7 @@ async fn handler(ValidatedBody(body): ValidatedBody) { } let app = Router::new().route("/foo", get(handler)); -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` ## Cannot implement both `FromRequest` and `FromRequestParts` @@ -518,8 +494,9 @@ wrapping another extractor: use axum::{ Router, routing::get, - extract::{FromRequest, FromRequestParts}, - http::{Request, request::Parts}, + extract::{FromRequest, Request, FromRequestParts}, + http::request::Parts, + body::Body, async_trait, }; use std::convert::Infallible; @@ -529,14 +506,13 @@ struct MyExtractor; // `MyExtractor` implements both `FromRequest` #[async_trait] -impl FromRequest for MyExtractor +impl FromRequest for MyExtractor where S: Send + Sync, - B: Send + 'static, { type Rejection = Infallible; - async fn from_request(req: Request, state: &S) -> Result { + async fn from_request(req: Request, state: &S) -> Result { // ... # todo!() } @@ -578,9 +554,8 @@ in your implementation. ```rust use axum::{ async_trait, - extract::{Extension, FromRequestParts, TypedHeader}, - headers::{authorization::Bearer, Authorization}, - http::{StatusCode, request::Parts}, + extract::{Extension, FromRequestParts}, + http::{StatusCode, HeaderMap, request::Parts}, response::{IntoResponse, Response}, routing::get, Router, @@ -604,10 +579,9 @@ where async fn from_request_parts(parts: &mut Parts, state: &S) -> Result { // You can either call them directly... - let TypedHeader(Authorization(token)) = - TypedHeader::>::from_request_parts(parts, state) - .await - .map_err(|err| err.into_response())?; + let headers = HeaderMap::from_request_parts(parts, state) + .await + .map_err(|err| match err {})?; // ... or use `extract` / `extract_with_state` from `RequestExt` / `RequestPartsExt` use axum::RequestPartsExt; @@ -626,9 +600,7 @@ async fn handler(user: AuthenticatedUser) { let state = State { /* ... */ }; let app = Router::new().route("/", get(handler)).layer(Extension(state)); -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` # Request body limits @@ -639,129 +611,6 @@ For security reasons, [`Bytes`] will, by default, not accept bodies larger than For more details, including how to disable this limit, see [`DefaultBodyLimit`]. -# Request body extractors - -Most of the time your request body type will be [`body::Body`] (a re-export -of [`hyper::Body`]), which is directly supported by all extractors. - -However if you're applying a tower middleware that changes the request body type -you might have to apply a different body type to some extractors: - -```rust -use std::{ - task::{Context, Poll}, - pin::Pin, -}; -use tower_http::map_request_body::MapRequestBodyLayer; -use axum::{ - extract::{self, BodyStream}, - body::{Body, HttpBody}, - routing::get, - http::{header::HeaderMap, Request}, - Router, -}; - -struct MyBody(B); - -impl HttpBody for MyBody -where - B: HttpBody + Unpin, -{ - type Data = B::Data; - type Error = B::Error; - - fn poll_data( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll>> { - Pin::new(&mut self.0).poll_data(cx) - } - - fn poll_trailers( - mut self: Pin<&mut Self>, - cx: &mut Context<'_>, - ) -> Poll, Self::Error>> { - Pin::new(&mut self.0).poll_trailers(cx) - } -} - -let app = Router::new() - .route( - "/string", - // `String` works directly with any body type - get(|_: String| async {}) - ) - .route( - "/body", - // `extract::Body` defaults to `axum::body::Body` - // but can be customized - get(|_: extract::RawBody>| async {}) - ) - .route( - "/body-stream", - // same for `extract::BodyStream` - get(|_: extract::BodyStream| async {}), - ) - .route( - // and `Request<_>` - "/request", - get(|_: Request>| async {}) - ) - // middleware that changes the request body type - .layer(MapRequestBodyLayer::new(MyBody)); -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; -``` - -# Running extractors from middleware - -Extractors can also be run from middleware: - -```rust -use axum::{ - middleware::{self, Next}, - extract::{TypedHeader, FromRequestParts}, - http::{Request, StatusCode}, - response::Response, - headers::authorization::{Authorization, Bearer}, - RequestPartsExt, Router, -}; - -async fn auth_middleware( - request: Request, - next: Next, -) -> Result -where - B: Send, -{ - // running extractors requires a `axum::http::request::Parts` - let (mut parts, body) = request.into_parts(); - - // `TypedHeader>` extracts the auth token - let auth: TypedHeader> = parts.extract() - .await - .map_err(|_| StatusCode::UNAUTHORIZED)?; - - if !token_is_valid(auth.token()) { - return Err(StatusCode::UNAUTHORIZED); - } - - // reconstruct the request - let request = Request::from_parts(parts, body); - - Ok(next.run(request).await) -} - -fn token_is_valid(token: &str) -> bool { - // ... - # false -} - -let app = Router::new().layer(middleware::from_fn(auth_middleware)); -# let _: Router<()> = app; -``` - # Wrapping extractors If you want write an extractor that generically wraps another extractor (that @@ -771,9 +620,10 @@ may or may not consume the request body) you should implement both ```rust use axum::{ Router, + body::Body, routing::get, - extract::{FromRequest, FromRequestParts}, - http::{Request, HeaderMap, request::Parts}, + extract::{Request, FromRequest, FromRequestParts}, + http::{HeaderMap, request::Parts}, async_trait, }; use std::time::{Instant, Duration}; @@ -806,15 +656,14 @@ where // and `FromRequest` #[async_trait] -impl FromRequest for Timing +impl FromRequest for Timing where - B: Send + 'static, S: Send + Sync, - T: FromRequest, + T: FromRequest, { type Rejection = T::Rejection; - async fn from_request(req: Request, state: &S) -> Result { + async fn from_request(req: Request, state: &S) -> Result { let start = Instant::now(); let extractor = T::from_request(req, state).await?; let duration = start.elapsed(); diff --git a/axum/src/docs/method_routing/layer.md b/axum/src/docs/method_routing/layer.md index cdf6f93342..7ceadd4dad 100644 --- a/axum/src/docs/method_routing/layer.md +++ b/axum/src/docs/method_routing/layer.md @@ -23,7 +23,5 @@ let app = Router::new().route( // All requests to `GET /` will be sent through `ConcurrencyLimitLayer` get(hander).layer(ConcurrencyLimitLayer::new(64)), ); -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` diff --git a/axum/src/docs/method_routing/route_layer.md b/axum/src/docs/method_routing/route_layer.md index f497e8b102..7a7ff36a37 100644 --- a/axum/src/docs/method_routing/route_layer.md +++ b/axum/src/docs/method_routing/route_layer.md @@ -28,7 +28,5 @@ let app = Router::new().route( // `GET /foo` with a valid token will receive `200 OK` // `GET /foo` with a invalid token will receive `401 Unauthorized` // `POST /FOO` with a invalid token will receive `405 Method Not Allowed` -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` diff --git a/axum/src/docs/middleware.md b/axum/src/docs/middleware.md index 90fa2cac48..70eda706c4 100644 --- a/axum/src/docs/middleware.md +++ b/axum/src/docs/middleware.md @@ -55,9 +55,7 @@ let app = Router::new() .layer(TraceLayer::new_for_http()) .layer(Extension(State {})) ); -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` # Commonly used middleware @@ -97,7 +95,7 @@ let app = Router::new() .layer(layer_one) .layer(layer_two) .layer(layer_three); -# let _: Router<(), axum::body::Body> = app; +# let _: Router = app; ``` Think of the middleware as being layered like an onion where each new layer @@ -156,7 +154,7 @@ let app = Router::new() .layer(layer_two) .layer(layer_three), ); -# let _: Router<(), axum::body::Body> = app; +# let _: Router = app; ``` `ServiceBuilder` works by composing all layers into one such that they run top @@ -223,7 +221,7 @@ A decent template for such a middleware could be: use axum::{ response::Response, body::Body, - http::Request, + extract::Request, }; use futures_util::future::BoxFuture; use tower::{Service, Layer}; @@ -245,9 +243,9 @@ struct MyMiddleware { inner: S, } -impl Service> for MyMiddleware +impl Service for MyMiddleware where - S: Service, Response = Response> + Send + 'static, + S: Service + Send + 'static, S::Future: Send + 'static, { type Response = S::Response; @@ -259,7 +257,7 @@ where self.inner.poll_ready(cx) } - fn call(&mut self, request: Request) -> Self::Future { + fn call(&mut self, request: Request) -> Self::Future { let future = self.inner.call(request); Box::pin(async move { let response: Response = future.await?; @@ -319,9 +317,7 @@ let app = Router::new() })) .layer(TimeoutLayer::new(Duration::from_secs(10))) ); -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` See [`error_handling`](crate::error_handling) for more details on axum's error @@ -376,9 +372,7 @@ let app = Router::new().route("/", get(handler)); let app = ServiceBuilder::new() .layer(some_backpressure_sensitive_middleware) .service(app); -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` However when applying middleware around your whole application in this way @@ -406,8 +400,7 @@ use axum::{ routing::get, middleware::{self, Next}, response::Response, - extract::State, - http::Request, + extract::{State, Request}, }; use tower::{Layer, Service}; use std::task::{Context, Poll}; @@ -477,17 +470,17 @@ State can be passed from middleware to handlers using [request extensions]: ```rust use axum::{ Router, - http::{Request, StatusCode}, + http::StatusCode, routing::get, response::{IntoResponse, Response}, middleware::{self, Next}, - extract::Extension, + extract::{Request, Extension}, }; #[derive(Clone)] struct CurrentUser { /* ... */ } -async fn auth(mut req: Request, next: Next) -> Result { +async fn auth(mut req: Request, next: Next) -> Result { let auth_header = req.headers() .get(http::header::AUTHORIZATION) .and_then(|header| header.to_str().ok()); @@ -523,7 +516,7 @@ async fn handler( let app = Router::new() .route("/", get(handler)) .route_layer(middleware::from_fn(auth)); -# let _: Router<()> = app; +# let _: Router = app; ``` [Response extensions] can also be used but note that request extensions are not @@ -546,16 +539,16 @@ use axum::{ ServiceExt, // for `into_make_service` response::Response, middleware::Next, - http::Request, + extract::Request, }; -async fn rewrite_request_uri(req: Request, next: Next) -> Response { +fn rewrite_request_uri(req: Request) -> Request { // ... - # next.run(req).await + # req } // this can be any `tower::Layer` -let middleware = axum::middleware::from_fn(rewrite_request_uri); +let middleware = tower::util::MapRequestLayer::new(rewrite_request_uri); let app = Router::new(); @@ -564,10 +557,8 @@ let app = Router::new(); let app_with_middleware = middleware.layer(app); # async { -axum::Server::bind(&"0.0.0.0:3000".parse().unwrap()) - .serve(app_with_middleware.into_make_service()) - .await - .unwrap(); +let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); +axum::serve(listener, app_with_middleware.into_make_service()).await.unwrap(); # }; ``` diff --git a/axum/src/docs/response.md b/axum/src/docs/response.md index 2afe476046..4e1d50b5e2 100644 --- a/axum/src/docs/response.md +++ b/axum/src/docs/response.md @@ -171,15 +171,15 @@ Use [`Response`](crate::response::Response) for more low level control: use axum::{ Json, response::{IntoResponse, Response}, - body::{Full, Bytes}, + body::Body, http::StatusCode, }; -async fn response() -> Response> { +async fn response() -> Response { Response::builder() .status(StatusCode::NOT_FOUND) .header("x-foo", "custom header") - .body(Full::from("not found")) + .body(Body::from("not found")) .unwrap() } ``` diff --git a/axum/src/docs/routing/fallback.md b/axum/src/docs/routing/fallback.md index 11b25896ef..582d0e2b2d 100644 --- a/axum/src/docs/routing/fallback.md +++ b/axum/src/docs/routing/fallback.md @@ -18,9 +18,7 @@ let app = Router::new() async fn fallback(uri: Uri) -> (StatusCode, String) { (StatusCode::NOT_FOUND, format!("No route for {}", uri)) } -# async { -# hyper::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` Fallbacks only apply to routes that aren't matched by anything in the @@ -40,10 +38,8 @@ async fn handler() {} let app = Router::new().fallback(handler); # async { -axum::Server::bind(&"0.0.0.0:3000".parse().unwrap()) - .serve(app.into_make_service()) - .await - .unwrap(); +let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); +axum::serve(listener, app).await.unwrap(); # }; ``` @@ -55,9 +51,7 @@ use axum::handler::HandlerWithoutStateExt; async fn handler() {} # async { -axum::Server::bind(&"0.0.0.0:3000".parse().unwrap()) - .serve(handler.into_make_service()) - .await - .unwrap(); +let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); +axum::serve(listener, handler.into_make_service()).await.unwrap(); # }; ``` diff --git a/axum/src/docs/routing/into_make_service_with_connect_info.md b/axum/src/docs/routing/into_make_service_with_connect_info.md index 05ee750c56..67dd652499 100644 --- a/axum/src/docs/routing/into_make_service_with_connect_info.md +++ b/axum/src/docs/routing/into_make_service_with_connect_info.md @@ -21,12 +21,8 @@ async fn handler(ConnectInfo(addr): ConnectInfo) -> String { } # async { -axum::Server::bind(&"0.0.0.0:3000".parse().unwrap()) - .serve( - app.into_make_service_with_connect_info::() - ) - .await - .expect("server failed"); +let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); +axum::serve(listener, app.into_make_service_with_connect_info::()).await.unwrap(); # }; ``` @@ -36,9 +32,9 @@ You can implement custom a [`Connected`] like so: use axum::{ extract::connect_info::{ConnectInfo, Connected}, routing::get, + serve::IncomingStream, Router, }; -use hyper::server::conn::AddrStream; let app = Router::new().route("/", get(handler)); @@ -53,8 +49,8 @@ struct MyConnectInfo { // ... } -impl Connected<&AddrStream> for MyConnectInfo { - fn connect_info(target: &AddrStream) -> Self { +impl Connected> for MyConnectInfo { + fn connect_info(target: IncomingStream<'_>) -> Self { MyConnectInfo { // ... } @@ -62,12 +58,8 @@ impl Connected<&AddrStream> for MyConnectInfo { } # async { -axum::Server::bind(&"0.0.0.0:3000".parse().unwrap()) - .serve( - app.into_make_service_with_connect_info::() - ) - .await - .expect("server failed"); +let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); +axum::serve(listener, app.into_make_service_with_connect_info::()).await.unwrap(); # }; ``` diff --git a/axum/src/docs/routing/nest.md b/axum/src/docs/routing/nest.md index b40d0fc951..c3f7308fdb 100644 --- a/axum/src/docs/routing/nest.md +++ b/axum/src/docs/routing/nest.md @@ -24,9 +24,7 @@ let app = Router::new().nest("/api", api_routes); // Our app now accepts // - GET /api/users/:id // - POST /api/teams -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` # How the URI changes @@ -59,9 +57,7 @@ async fn users_get(Path(params): Path>) { let users_api = Router::new().route("/users/:id", get(users_get)); let app = Router::new().nest("/:version/api", users_api); -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` # Differences from wildcard routes @@ -83,9 +79,7 @@ let app = Router::new() // `uri` will contain `/foo` })) .nest("/bar", nested_router); -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` # Fallbacks diff --git a/axum/src/docs/routing/route.md b/axum/src/docs/routing/route.md index ae425142fc..394ae59b49 100644 --- a/axum/src/docs/routing/route.md +++ b/axum/src/docs/routing/route.md @@ -77,9 +77,7 @@ async fn get_root() {} async fn post_root() {} async fn delete_root() {} -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` # More examples @@ -105,9 +103,7 @@ async fn show_user(Path(id): Path) {} async fn do_users_action(Path((version, id)): Path<(String, u64)>) {} async fn serve_asset(Path(path): Path) {} -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` # Panics @@ -120,9 +116,7 @@ use axum::{routing::get, Router}; let app = Router::new() .route("/", get(|| async {})) .route("/", get(|| async {})); -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` The static route `/foo` and the dynamic route `/:key` are not considered to diff --git a/axum/src/docs/routing/route_layer.md b/axum/src/docs/routing/route_layer.md index fe5b8faa7d..5e60eaf5d3 100644 --- a/axum/src/docs/routing/route_layer.md +++ b/axum/src/docs/routing/route_layer.md @@ -26,7 +26,5 @@ let app = Router::new() // `GET /foo` with a valid token will receive `200 OK` // `GET /foo` with a invalid token will receive `401 Unauthorized` // `GET /not-found` with a invalid token will receive `404 Not Found` -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` diff --git a/axum/src/docs/routing/route_service.md b/axum/src/docs/routing/route_service.md index 1be229e4c6..7f016105df 100644 --- a/axum/src/docs/routing/route_service.md +++ b/axum/src/docs/routing/route_service.md @@ -7,7 +7,8 @@ use axum::{ Router, body::Body, routing::{any_service, get_service}, - http::{Request, StatusCode}, + extract::Request, + http::StatusCode, error_handling::HandleErrorLayer, }; use tower_http::services::ServeFile; @@ -22,7 +23,7 @@ let app = Router::new() // Services whose response body is not `axum::body::BoxBody` // can be wrapped in `axum::routing::any_service` (or one of the other routing filters) // to have the response body mapped - any_service(service_fn(|_: Request| async { + any_service(service_fn(|_: Request| async { let res = Response::new(Body::from("Hi from `GET /`")); Ok::<_, Infallible>(res) })) @@ -31,9 +32,8 @@ let app = Router::new() "/foo", // This service's response body is `axum::body::BoxBody` so // it can be routed to directly. - service_fn(|req: Request| async move { + service_fn(|req: Request| async move { let body = Body::from(format!("Hi from `{} /foo`", req.method())); - let body = axum::body::boxed(body); let res = Response::new(body); Ok::<_, Infallible>(res) }) @@ -43,9 +43,7 @@ let app = Router::new() "/static/Cargo.toml", ServeFile::new("Cargo.toml"), ); -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` Routing to arbitrary services in this way has complications for backpressure @@ -64,9 +62,7 @@ let app = Router::new().route_service( "/", Router::new().route("/foo", get(|| async {})), ); -# async { -# axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -# }; +# let _: Router = app; ``` Use [`Router::nest`] instead. diff --git a/axum/src/docs/routing/with_state.md b/axum/src/docs/routing/with_state.md index 3f9c815132..bece920fe0 100644 --- a/axum/src/docs/routing/with_state.md +++ b/axum/src/docs/routing/with_state.md @@ -13,9 +13,8 @@ let routes = Router::new() .with_state(AppState {}); # async { -axum::Server::bind(&"0.0.0.0:3000".parse().unwrap()) - .serve(routes.into_make_service()) - .await; +let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); +axum::serve(listener, routes).await.unwrap(); # }; ``` @@ -40,9 +39,8 @@ fn routes() -> Router { let routes = routes().with_state(AppState {}); # async { -axum::Server::bind(&"0.0.0.0:3000".parse().unwrap()) - .serve(routes.into_make_service()) - .await; +let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); +axum::serve(listener, routes).await.unwrap(); # }; ``` @@ -64,9 +62,8 @@ fn routes(state: AppState) -> Router { let routes = routes(AppState {}); # async { -axum::Server::bind(&"0.0.0.0:3000".parse().unwrap()) - .serve(routes.into_make_service()) - .await; +let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); +axum::serve(listener, routes).await.unwrap(); # }; ``` @@ -92,9 +89,8 @@ fn routes(state: AppState) -> Router { let routes = Router::new().nest("/api", routes(AppState {})); # async { -axum::Server::bind(&"0.0.0.0:3000".parse().unwrap()) - .serve(routes.into_make_service()) - .await; +let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); +axum::serve(listener, routes).await.unwrap(); # }; ``` @@ -133,9 +129,8 @@ let router: Router<()> = router.with_state(AppState {}); // You cannot call `into_make_service` on a `Router` // because it is still missing an `AppState`. # async { -axum::Server::bind(&"0.0.0.0:3000".parse().unwrap()) - .serve(router.into_make_service()) - .await; +let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); +axum::serve(listener, router).await.unwrap(); # }; ``` @@ -163,9 +158,8 @@ let final_router: Router<()> = string_router.with_state("foo".to_owned()); // Since we have a `Router<()>` we can run it. # async { -axum::Server::bind(&"0.0.0.0:3000".parse().unwrap()) - .serve(final_router.into_make_service()) - .await; +let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); +axum::serve(listener, final_router).await.unwrap(); # }; ``` @@ -190,9 +184,8 @@ let app = routes(AppState {}); // We can only call `Router::into_make_service` on a `Router<()>` // but `app` is a `Router` # async { -axum::Server::bind(&"0.0.0.0:3000".parse().unwrap()) - .serve(app.into_make_service()) - .await; +let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); +axum::serve(listener, app).await.unwrap(); # }; ``` @@ -214,9 +207,8 @@ let app = routes(AppState {}); // We can now call `Router::into_make_service` # async { -axum::Server::bind(&"0.0.0.0:3000".parse().unwrap()) - .serve(app.into_make_service()) - .await; +let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); +axum::serve(listener, app).await.unwrap(); # }; ``` diff --git a/axum/src/extension.rs b/axum/src/extension.rs index d66c9466b9..42f208c4d8 100644 --- a/axum/src/extension.rs +++ b/axum/src/extension.rs @@ -40,9 +40,7 @@ use tower_service::Service; /// // Add middleware that inserts the state into all incoming request's /// // extensions. /// .layer(Extension(state)); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` /// /// If the extension is missing it will reject the request with a `500 Internal diff --git a/axum/src/extract/connect_info.rs b/axum/src/extract/connect_info.rs index f22b89815c..216022e857 100644 --- a/axum/src/extract/connect_info.rs +++ b/axum/src/extract/connect_info.rs @@ -5,7 +5,7 @@ //! [`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info use super::{Extension, FromRequestParts}; -use crate::middleware::AddExtension; +use crate::{middleware::AddExtension, serve::IncomingStream}; use async_trait::async_trait; use http::request::Parts; use hyper::server::conn::AddrStream; @@ -89,6 +89,12 @@ impl Connected<&AddrStream> for SocketAddr { } } +impl Connected> for SocketAddr { + fn connect_info(target: IncomingStream<'_>) -> Self { + target.remote_addr() + } +} + impl Service for IntoMakeServiceWithConnectInfo where S: Clone, @@ -213,8 +219,9 @@ where #[cfg(test)] mod tests { use super::*; - use crate::{routing::get, test_helpers::TestClient, Router, Server}; - use std::net::{SocketAddr, TcpListener}; + use crate::{routing::get, test_helpers::TestClient, Router}; + use std::net::SocketAddr; + use tokio::net::TcpListener; #[crate::test] async fn socket_addr() { @@ -222,17 +229,19 @@ mod tests { format!("{addr}") } - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); let (tx, rx) = tokio::sync::oneshot::channel(); tokio::spawn(async move { let app = Router::new().route("/", get(handler)); - let server = Server::from_tcp(listener) - .unwrap() - .serve(app.into_make_service_with_connect_info::()); tx.send(()).unwrap(); - server.await.expect("server error"); + crate::serve( + listener, + app.into_make_service_with_connect_info::(), + ) + .await + .unwrap(); }); rx.await.unwrap(); @@ -250,8 +259,8 @@ mod tests { value: &'static str, } - impl Connected<&AddrStream> for MyConnectInfo { - fn connect_info(_target: &AddrStream) -> Self { + impl Connected> for MyConnectInfo { + fn connect_info(_target: IncomingStream<'_>) -> Self { Self { value: "it worked!", } @@ -262,17 +271,19 @@ mod tests { addr.value } - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); let (tx, rx) = tokio::sync::oneshot::channel(); tokio::spawn(async move { let app = Router::new().route("/", get(handler)); - let server = Server::from_tcp(listener) - .unwrap() - .serve(app.into_make_service_with_connect_info::()); tx.send(()).unwrap(); - server.await.expect("server error"); + crate::serve( + listener, + app.into_make_service_with_connect_info::(), + ) + .await + .unwrap(); }); rx.await.unwrap(); @@ -306,7 +317,7 @@ mod tests { format!("{addr}") } - let listener = TcpListener::bind("127.0.0.1:0").unwrap(); + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let addr = listener.local_addr().unwrap(); tokio::spawn(async move { @@ -314,10 +325,12 @@ mod tests { .route("/", get(handler)) .layer(MockConnectInfo(SocketAddr::from(([0, 0, 0, 0], 1337)))); - let server = Server::from_tcp(listener) - .unwrap() - .serve(app.into_make_service_with_connect_info::()); - server.await.expect("server error"); + crate::serve( + listener, + app.into_make_service_with_connect_info::(), + ) + .await + .unwrap(); }); let client = reqwest::Client::new(); diff --git a/axum/src/extract/matched_path.rs b/axum/src/extract/matched_path.rs index c4f9984e24..ae7d130d76 100644 --- a/axum/src/extract/matched_path.rs +++ b/axum/src/extract/matched_path.rs @@ -20,9 +20,7 @@ use std::{collections::HashMap, sync::Arc}; /// // `path` will be "/users/:id" /// }) /// ); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` /// /// # Accessing `MatchedPath` via extensions @@ -35,8 +33,7 @@ use std::{collections::HashMap, sync::Arc}; /// ``` /// use axum::{ /// Router, -/// extract::MatchedPath, -/// http::Request, +/// extract::{Request, MatchedPath}, /// routing::get, /// }; /// use tower_http::trace::TraceLayer; @@ -65,13 +62,12 @@ use std::{collections::HashMap, sync::Arc}; /// Router, /// RequestExt, /// routing::get, -/// extract::{MatchedPath, rejection::MatchedPathRejection}, +/// extract::{Request, MatchedPath, rejection::MatchedPathRejection}, /// middleware::map_request, -/// http::Request, /// body::Body, /// }; /// -/// async fn access_matched_path(mut request: Request) -> Request { +/// async fn access_matched_path(mut request: Request) -> Request { /// // if `/foo/bar` is called this will be `Err(_)` since that matches /// // a nested route /// let matched_path: Result = @@ -172,14 +168,14 @@ fn append_nested_matched_path(matched_path: &Arc, extensions: &http::Extens mod tests { use super::*; use crate::{ - body::Body, + extract::Request, handler::HandlerWithoutStateExt, middleware::map_request, routing::{any, get}, test_helpers::*, Router, }; - use http::{Request, StatusCode}; + use http::StatusCode; #[crate::test] async fn extracting_on_handler() { @@ -365,7 +361,7 @@ mod tests { let app = Router::new().route( "/*path", - any(|req: Request| { + any(|req: Request| { Router::new() .nest("/", Router::new().route("/foo", get(|| async {}))) .oneshot(req) @@ -380,7 +376,7 @@ mod tests { #[crate::test] async fn cant_extract_in_fallback() { - async fn handler(path: Option, req: Request) { + async fn handler(path: Option, req: Request) { assert!(path.is_none()); assert!(req.extensions().get::().is_none()); } diff --git a/axum/src/extract/mod.rs b/axum/src/extract/mod.rs index cb4ebcd92c..fce1b01081 100644 --- a/axum/src/extract/mod.rs +++ b/axum/src/extract/mod.rs @@ -17,7 +17,7 @@ mod request_parts; mod state; #[doc(inline)] -pub use axum_core::extract::{DefaultBodyLimit, FromRef, FromRequest, FromRequestParts}; +pub use axum_core::extract::{DefaultBodyLimit, FromRef, FromRequest, FromRequestParts, Request}; #[cfg(feature = "macros")] pub use axum_macros::{FromRef, FromRequest, FromRequestParts}; @@ -29,7 +29,6 @@ pub use self::{ path::{Path, RawPathParams}, raw_form::RawForm, raw_query::RawQuery, - request_parts::{BodyStream, RawBody}, state::State, }; @@ -77,10 +76,6 @@ pub use self::request_parts::OriginalUri; #[doc(inline)] pub use self::ws::WebSocketUpgrade; -#[cfg(feature = "headers")] -#[doc(no_inline)] -pub use crate::TypedHeader; - // this is duplicated in `axum-extra/src/extract/form.rs` pub(super) fn has_content_type(headers: &HeaderMap, expected_content_type: &mime::Mime) -> bool { let content_type = if let Some(content_type) = headers.get(header::CONTENT_TYPE) { diff --git a/axum/src/extract/multipart.rs b/axum/src/extract/multipart.rs index b7f2c10322..9d1518c8e9 100644 --- a/axum/src/extract/multipart.rs +++ b/axum/src/extract/multipart.rs @@ -2,17 +2,17 @@ //! //! See [`Multipart`] for more details. -use super::{BodyStream, FromRequest}; -use crate::body::{Bytes, HttpBody}; -use crate::BoxError; +use super::{FromRequest, Request}; +use crate::body::Bytes; use async_trait::async_trait; use axum_core::__composite_rejection as composite_rejection; use axum_core::__define_rejection as define_rejection; +use axum_core::body::Body; use axum_core::response::{IntoResponse, Response}; use axum_core::RequestExt; use futures_util::stream::Stream; use http::header::{HeaderMap, CONTENT_TYPE}; -use http::{Request, StatusCode}; +use http::StatusCode; use std::error::Error; use std::{ fmt, @@ -48,9 +48,7 @@ use std::{ /// } /// /// let app = Router::new().route("/upload", post(upload)); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` #[cfg_attr(docsrs, doc(cfg(feature = "multipart")))] #[derive(Debug)] @@ -59,22 +57,18 @@ pub struct Multipart { } #[async_trait] -impl FromRequest for Multipart +impl FromRequest for Multipart where - B: HttpBody + Send + 'static, - B::Data: Into, - B::Error: Into, S: Send + Sync, { type Rejection = MultipartRejection; - async fn from_request(req: Request, state: &S) -> Result { + async fn from_request(req: Request, _state: &S) -> Result { let boundary = parse_boundary(req.headers()).ok_or(InvalidBoundary)?; - let stream_result = match req.with_limited_body() { - Ok(limited) => BodyStream::from_request(limited, state).await, - Err(unlimited) => BodyStream::from_request(unlimited, state).await, + let stream = match req.with_limited_body() { + Ok(limited) => Body::new(limited), + Err(unlimited) => unlimited.into_body(), }; - let stream = stream_result.unwrap_or_else(|err| match err {}); let multipart = multer::Multipart::new(stream, boundary); Ok(Self { inner: multipart }) } @@ -310,7 +304,7 @@ mod tests { use axum_core::extract::DefaultBodyLimit; use super::*; - use crate::{body::Body, response::IntoResponse, routing::post, test_helpers::*, Router}; + use crate::{response::IntoResponse, routing::post, test_helpers::*, Router}; #[crate::test] async fn content_type_with_encoding() { @@ -346,7 +340,9 @@ mod tests { // No need for this to be a #[test], we just want to make sure it compiles fn _multipart_from_request_limited() { async fn handler(_: Multipart) {} - let _app: Router<(), http_body::Limited> = Router::new().route("/", post(handler)); + let _app: Router = Router::new() + .route("/", post(handler)) + .layer(tower_http::limit::RequestBodyLimitLayer::new(1024)); } #[crate::test] diff --git a/axum/src/extract/path/mod.rs b/axum/src/extract/path/mod.rs index 189e476e5c..5f7c710715 100644 --- a/axum/src/extract/path/mod.rs +++ b/axum/src/extract/path/mod.rs @@ -42,9 +42,7 @@ use std::{fmt, sync::Arc}; /// } /// /// let app = Router::new().route("/users/:user_id/team/:team_id", get(users_teams_show)); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` /// /// If the path contains only one parameter, then you can omit the tuple. @@ -62,9 +60,7 @@ use std::{fmt, sync::Arc}; /// } /// /// let app = Router::new().route("/users/:user_id", get(user_info)); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` /// /// Path segments also can be deserialized into any type that implements @@ -103,9 +99,7 @@ use std::{fmt, sync::Arc}; /// "/users/:user_id/team/:team_id", /// get(users_teams_show).post(users_teams_create), /// ); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` /// /// If you wish to capture all path parameters you can use `HashMap` or `Vec`: @@ -132,9 +126,7 @@ use std::{fmt, sync::Arc}; /// /// let app = Router::new() /// .route("/users/:user_id/team/:team_id", get(params_map).post(params_vec)); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` /// /// # Providing detailed rejection output diff --git a/axum/src/extract/query.rs b/axum/src/extract/query.rs index f9551e076d..81b28b61cd 100644 --- a/axum/src/extract/query.rs +++ b/axum/src/extract/query.rs @@ -32,9 +32,7 @@ use serde::de::DeserializeOwned; /// } /// /// let app = Router::new().route("/list_things", get(list_things)); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` /// /// If the query string cannot be parsed it will reject the request with a `400 @@ -71,7 +69,7 @@ mod tests { use crate::{routing::get, test_helpers::TestClient, Router}; use super::*; - use axum_core::extract::FromRequest; + use axum_core::{body::Body, extract::FromRequest}; use http::{Request, StatusCode}; use serde::Deserialize; use std::fmt::Debug; @@ -80,7 +78,10 @@ mod tests { where T: DeserializeOwned + PartialEq + Debug, { - let req = Request::builder().uri(uri.as_ref()).body(()).unwrap(); + let req = Request::builder() + .uri(uri.as_ref()) + .body(Body::empty()) + .unwrap(); assert_eq!(Query::::from_request(req, &()).await.unwrap().0, value); } diff --git a/axum/src/extract/raw_form.rs b/axum/src/extract/raw_form.rs index 830d8b62ae..f9c7d3572c 100644 --- a/axum/src/extract/raw_form.rs +++ b/axum/src/extract/raw_form.rs @@ -1,15 +1,13 @@ use async_trait::async_trait; -use axum_core::extract::FromRequest; +use axum_core::extract::{FromRequest, Request}; use bytes::{Bytes, BytesMut}; -use http::{Method, Request}; +use http::Method; use super::{ has_content_type, rejection::{InvalidFormContentType, RawFormRejection}, }; -use crate::{body::HttpBody, BoxError}; - /// Extractor that extracts raw form requests. /// /// For `GET` requests it will extract the raw query. For other methods it extracts the raw @@ -27,24 +25,19 @@ use crate::{body::HttpBody, BoxError}; /// async fn handler(RawForm(form): RawForm) {} /// /// let app = Router::new().route("/", get(handler)); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` #[derive(Debug)] pub struct RawForm(pub Bytes); #[async_trait] -impl FromRequest for RawForm +impl FromRequest for RawForm where - B: HttpBody + Send + 'static, - B::Data: Send, - B::Error: Into, S: Send + Sync, { type Rejection = RawFormRejection; - async fn from_request(req: Request, state: &S) -> Result { + async fn from_request(req: Request, state: &S) -> Result { if req.method() == Method::GET { let mut bytes = BytesMut::new(); @@ -65,20 +58,15 @@ where #[cfg(test)] mod tests { + use axum_core::body::Body; use http::{header::CONTENT_TYPE, Request}; use super::{InvalidFormContentType, RawForm, RawFormRejection}; - use crate::{ - body::{Bytes, Empty, Full}, - extract::FromRequest, - }; + use crate::extract::FromRequest; async fn check_query(uri: &str, value: &[u8]) { - let req = Request::builder() - .uri(uri) - .body(Empty::::new()) - .unwrap(); + let req = Request::builder().uri(uri).body(Body::empty()).unwrap(); assert_eq!(RawForm::from_request(req, &()).await.unwrap().0, value); } @@ -86,7 +74,7 @@ mod tests { async fn check_body(body: &'static [u8]) { let req = Request::post("http://example.com/test") .header(CONTENT_TYPE, mime::APPLICATION_WWW_FORM_URLENCODED.as_ref()) - .body(Full::new(Bytes::from(body))) + .body(Body::from(body)) .unwrap(); assert_eq!(RawForm::from_request(req, &()).await.unwrap().0, body); @@ -109,7 +97,7 @@ mod tests { #[crate::test] async fn test_incorrect_content_type() { let req = Request::post("http://example.com/test") - .body(Full::::from(Bytes::from("page=0&size=10"))) + .body(Body::from("page=0&size=10")) .unwrap(); assert!(matches!( diff --git a/axum/src/extract/raw_query.rs b/axum/src/extract/raw_query.rs index 98a60b0930..d8c56f84a4 100644 --- a/axum/src/extract/raw_query.rs +++ b/axum/src/extract/raw_query.rs @@ -20,9 +20,7 @@ use std::convert::Infallible; /// } /// /// let app = Router::new().route("/users", get(handler)); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` #[derive(Debug)] pub struct RawQuery(pub Option); diff --git a/axum/src/extract/rejection.rs b/axum/src/extract/rejection.rs index caaab06d86..6a395f5b29 100644 --- a/axum/src/extract/rejection.rs +++ b/axum/src/extract/rejection.rs @@ -207,6 +207,3 @@ composite_rejection! { MatchedPathMissing, } } - -#[cfg(feature = "headers")] -pub use crate::typed_header::{TypedHeaderRejection, TypedHeaderRejectionReason}; diff --git a/axum/src/extract/request_parts.rs b/axum/src/extract/request_parts.rs index 9af618fa20..9756665b6c 100644 --- a/axum/src/extract/request_parts.rs +++ b/axum/src/extract/request_parts.rs @@ -1,18 +1,7 @@ -use super::{Extension, FromRequest, FromRequestParts}; -use crate::{ - body::{Body, Bytes, HttpBody}, - BoxError, Error, -}; +use super::{Extension, FromRequestParts}; use async_trait::async_trait; -use futures_util::stream::Stream; -use http::{request::Parts, Request, Uri}; -use std::{ - convert::Infallible, - fmt, - pin::Pin, - task::{Context, Poll}, -}; -use sync_wrapper::SyncWrapper; +use http::{request::Parts, Uri}; +use std::convert::Infallible; /// Extractor that gets the original request URI regardless of nesting. /// @@ -39,9 +28,7 @@ use sync_wrapper::SyncWrapper; /// ); /// /// let app = Router::new().nest("/api", api_routes); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` /// /// # Extracting via request extensions @@ -76,9 +63,7 @@ use sync_wrapper::SyncWrapper; /// ); /// /// let app = Router::new().nest("/api", api_routes); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` #[cfg(feature = "original-uri")] #[derive(Debug, Clone)] @@ -104,128 +89,6 @@ where #[cfg(feature = "original-uri")] axum_core::__impl_deref!(OriginalUri: Uri); -/// Extractor that extracts the request body as a [`Stream`]. -/// -/// Since extracting the request body requires consuming it, the `BodyStream` extractor must be -/// *last* if there are multiple extractors in a handler. -/// See ["the order of extractors"][order-of-extractors] -/// -/// [order-of-extractors]: crate::extract#the-order-of-extractors -/// -/// # Example -/// -/// ```rust,no_run -/// use axum::{ -/// extract::BodyStream, -/// routing::get, -/// Router, -/// }; -/// use futures_util::StreamExt; -/// -/// async fn handler(mut stream: BodyStream) { -/// while let Some(chunk) = stream.next().await { -/// // ... -/// } -/// } -/// -/// let app = Router::new().route("/users", get(handler)); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; -/// ``` -/// -/// [`Stream`]: https://docs.rs/futures/latest/futures/stream/trait.Stream.html -/// [`body::Body`]: crate::body::Body -pub struct BodyStream( - SyncWrapper + Send + 'static>>>, -); - -impl Stream for BodyStream { - type Item = Result; - - fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { - Pin::new(self.0.get_mut()).poll_data(cx) - } -} - -#[async_trait] -impl FromRequest for BodyStream -where - B: HttpBody + Send + 'static, - B::Data: Into, - B::Error: Into, - S: Send + Sync, -{ - type Rejection = Infallible; - - async fn from_request(req: Request, _state: &S) -> Result { - let body = req - .into_body() - .map_data(Into::into) - .map_err(|err| Error::new(err.into())); - let stream = BodyStream(SyncWrapper::new(Box::pin(body))); - Ok(stream) - } -} - -impl fmt::Debug for BodyStream { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_tuple("BodyStream").finish() - } -} - -#[test] -fn body_stream_traits() { - crate::test_helpers::assert_send::(); - crate::test_helpers::assert_sync::(); -} - -/// Extractor that extracts the raw request body. -/// -/// Since extracting the raw request body requires consuming it, the `RawBody` extractor must be -/// *last* if there are multiple extractors in a handler. See ["the order of extractors"][order-of-extractors] -/// -/// [order-of-extractors]: crate::extract#the-order-of-extractors -/// -/// # Example -/// -/// ```rust,no_run -/// use axum::{ -/// extract::RawBody, -/// routing::get, -/// Router, -/// }; -/// use futures_util::StreamExt; -/// -/// async fn handler(RawBody(body): RawBody) { -/// // ... -/// } -/// -/// let app = Router::new().route("/users", get(handler)); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; -/// ``` -/// -/// [`body::Body`]: crate::body::Body -#[derive(Debug, Default, Clone)] -pub struct RawBody(pub B); - -#[async_trait] -impl FromRequest for RawBody -where - B: Send, - S: Send + Sync, -{ - type Rejection = Infallible; - - async fn from_request(req: Request, _state: &S) -> Result { - Ok(Self(req.into_body())) - } -} - -axum_core::__impl_deref!(RawBody); - #[cfg(test)] mod tests { use crate::{extract::Extension, routing::get, test_helpers::*, Router}; diff --git a/axum/src/extract/state.rs b/axum/src/extract/state.rs index e2307d391c..1592a813df 100644 --- a/axum/src/extract/state.rs +++ b/axum/src/extract/state.rs @@ -131,13 +131,11 @@ use std::{ /// let method_router_with_state = get(handler) /// // provide the state so the handler can access it /// .with_state(state); +/// # let _: axum::routing::MethodRouter = method_router_with_state; /// /// async fn handler(State(state): State) { /// // use `state`... /// } -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(method_router_with_state.into_make_service()).await.unwrap(); -/// # }; /// ``` /// /// # With `Handler` @@ -158,10 +156,8 @@ use std::{ /// let handler_with_state = handler.with_state(state); /// /// # async { -/// axum::Server::bind(&"0.0.0.0:3000".parse().unwrap()) -/// .serve(handler_with_state.into_make_service()) -/// .await -/// .expect("server failed"); +/// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); +/// axum::serve(listener, handler_with_state.into_make_service()).await.unwrap(); /// # }; /// ``` /// diff --git a/axum/src/extract/ws.rs b/axum/src/extract/ws.rs index d785a8007d..991ee0b8bb 100644 --- a/axum/src/extract/ws.rs +++ b/axum/src/extract/ws.rs @@ -31,9 +31,7 @@ //! } //! } //! } -//! # async { -//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -//! # }; +//! # let _: Router = app; //! ``` //! //! # Passing data and/or state to an `on_upgrade` callback @@ -62,9 +60,7 @@ //! let app = Router::new() //! .route("/ws", get(handler)) //! .with_state(AppState { /* ... */ }); -//! # async { -//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -//! # }; +//! # let _: Router = app; //! ``` //! //! # Read and write concurrently @@ -96,12 +92,9 @@ use self::rejection::*; use super::FromRequestParts; -use crate::{ - body::{self, Bytes}, - response::Response, - Error, -}; +use crate::{body::Bytes, response::Response, Error}; use async_trait::async_trait; +use axum_core::body::Body; use futures_util::{ sink::{Sink, SinkExt}, stream::{Stream, StreamExt}, @@ -111,7 +104,6 @@ use http::{ request::Parts, Method, StatusCode, }; -use hyper::upgrade::{OnUpgrade, Upgraded}; use sha1::{Digest, Sha1}; use std::{ borrow::Cow, @@ -135,12 +127,12 @@ use tokio_tungstenite::{ /// /// See the [module docs](self) for an example. #[cfg_attr(docsrs, doc(cfg(feature = "ws")))] -pub struct WebSocketUpgrade { +pub struct WebSocketUpgrade { config: WebSocketConfig, /// The chosen protocol sent in the `Sec-WebSocket-Protocol` header of the response. protocol: Option, sec_websocket_key: HeaderValue, - on_upgrade: OnUpgrade, + on_upgrade: hyper1::upgrade::OnUpgrade, on_failed_upgrade: F, sec_websocket_protocol: Option, } @@ -209,9 +201,7 @@ impl WebSocketUpgrade { /// // ... /// }) /// } - /// # async { - /// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); - /// # }; + /// # let _: Router = app; /// ``` pub fn protocols(mut self, protocols: I) -> Self where @@ -268,7 +258,7 @@ impl WebSocketUpgrade { /// ``` pub fn on_failed_upgrade(self, callback: C) -> WebSocketUpgrade where - C: OnFailedUpdgrade, + C: OnFailedUpgrade, { WebSocketUpgrade { config: self.config, @@ -287,7 +277,7 @@ impl WebSocketUpgrade { where C: FnOnce(WebSocket) -> Fut + Send + 'static, Fut: Future + Send + 'static, - F: OnFailedUpdgrade, + F: OnFailedUpgrade, { let on_upgrade = self.on_upgrade; let config = self.config; @@ -332,19 +322,19 @@ impl WebSocketUpgrade { builder = builder.header(header::SEC_WEBSOCKET_PROTOCOL, protocol); } - builder.body(body::boxed(body::Empty::new())).unwrap() + builder.body(Body::empty()).unwrap() } } /// What to do when a connection upgrade fails. /// /// See [`WebSocketUpgrade::on_failed_upgrade`] for more details. -pub trait OnFailedUpdgrade: Send + 'static { +pub trait OnFailedUpgrade: Send + 'static { /// Call the callback. fn call(self, error: Error); } -impl OnFailedUpdgrade for F +impl OnFailedUpgrade for F where F: FnOnce(Error) + Send + 'static, { @@ -353,20 +343,20 @@ where } } -/// The default `OnFailedUpdgrade` used by `WebSocketUpgrade`. +/// The default `OnFailedUpgrade` used by `WebSocketUpgrade`. /// /// It simply ignores the error. #[non_exhaustive] #[derive(Debug)] -pub struct DefaultOnFailedUpdgrade; +pub struct DefaultOnFailedUpgrade; -impl OnFailedUpdgrade for DefaultOnFailedUpdgrade { +impl OnFailedUpgrade for DefaultOnFailedUpgrade { #[inline] fn call(self, _error: Error) {} } #[async_trait] -impl FromRequestParts for WebSocketUpgrade +impl FromRequestParts for WebSocketUpgrade where S: Send + Sync, { @@ -396,7 +386,7 @@ where let on_upgrade = parts .extensions - .remove::() + .remove::() .ok_or(ConnectionNotUpgradable)?; let sec_websocket_protocol = parts.headers.get(header::SEC_WEBSOCKET_PROTOCOL).cloned(); @@ -407,7 +397,7 @@ where sec_websocket_key, on_upgrade, sec_websocket_protocol, - on_failed_upgrade: DefaultOnFailedUpdgrade, + on_failed_upgrade: DefaultOnFailedUpgrade, }) } } @@ -439,7 +429,7 @@ fn header_contains(headers: &HeaderMap, key: HeaderName, value: &'static str) -> /// See [the module level documentation](self) for more details. #[derive(Debug)] pub struct WebSocket { - inner: WebSocketStream, + inner: WebSocketStream, protocol: Option, } diff --git a/axum/src/form.rs b/axum/src/form.rs index 208049130f..b197e6e27f 100644 --- a/axum/src/form.rs +++ b/axum/src/form.rs @@ -1,11 +1,10 @@ -use crate::body::HttpBody; +use crate::extract::Request; use crate::extract::{rejection::*, FromRequest, RawForm}; -use crate::BoxError; use async_trait::async_trait; use axum_core::response::{IntoResponse, Response}; use axum_core::RequestExt; use http::header::CONTENT_TYPE; -use http::{Request, StatusCode}; +use http::StatusCode; use serde::de::DeserializeOwned; use serde::Serialize; @@ -64,17 +63,14 @@ use serde::Serialize; pub struct Form(pub T); #[async_trait] -impl FromRequest for Form +impl FromRequest for Form where T: DeserializeOwned, - B: HttpBody + Send + 'static, - B::Data: Send, - B::Error: Into, S: Send + Sync, { type Rejection = FormRejection; - async fn from_request(req: Request, _state: &S) -> Result { + async fn from_request(req: Request, _state: &S) -> Result { let is_get_or_head = req.method() == http::Method::GET || req.method() == http::Method::HEAD; @@ -118,15 +114,15 @@ axum_core::__impl_deref!(Form); #[cfg(test)] mod tests { - use super::*; use crate::{ - body::{Empty, Full}, routing::{on, MethodFilter}, test_helpers::TestClient, Router, }; - use bytes::Bytes; - use http::{header::CONTENT_TYPE, Method, Request}; + + use super::*; + use axum_core::body::Body; + use http::{Method, Request}; use mime::APPLICATION_WWW_FORM_URLENCODED; use serde::{Deserialize, Serialize}; use std::fmt::Debug; @@ -140,7 +136,7 @@ mod tests { async fn check_query(uri: impl AsRef, value: T) { let req = Request::builder() .uri(uri.as_ref()) - .body(Empty::::new()) + .body(Body::empty()) .unwrap(); assert_eq!(Form::::from_request(req, &()).await.unwrap().0, value); } @@ -150,9 +146,7 @@ mod tests { .uri("http://example.com/test") .method(Method::POST) .header(CONTENT_TYPE, APPLICATION_WWW_FORM_URLENCODED.as_ref()) - .body(Full::::new( - serde_urlencoded::to_string(&value).unwrap().into(), - )) + .body(Body::from(serde_urlencoded::to_string(&value).unwrap())) .unwrap(); assert_eq!(Form::::from_request(req, &()).await.unwrap().0, value); } @@ -214,13 +208,12 @@ mod tests { .uri("http://example.com/test") .method(Method::POST) .header(CONTENT_TYPE, mime::APPLICATION_JSON.as_ref()) - .body(Full::::new( + .body(Body::from( serde_urlencoded::to_string(&Pagination { size: Some(10), page: None, }) - .unwrap() - .into(), + .unwrap(), )) .unwrap(); assert!(matches!( diff --git a/axum/src/handler/future.rs b/axum/src/handler/future.rs index 59487c31b2..751984d0c6 100644 --- a/axum/src/handler/future.rs +++ b/axum/src/handler/future.rs @@ -1,8 +1,8 @@ //! Handler future types. use crate::response::Response; +use axum_core::extract::Request; use futures_util::future::Map; -use http::Request; use pin_project_lite::pin_project; use std::{convert::Infallible, future::Future, pin::Pin, task::Context}; use tower::util::Oneshot; @@ -19,29 +19,29 @@ opaque_future! { pin_project! { /// The response future for [`Layered`](super::Layered). - pub struct LayeredFuture + pub struct LayeredFuture where - S: Service>, + S: Service, { #[pin] - inner: Map>, fn(Result) -> Response>, + inner: Map, fn(Result) -> Response>, } } -impl LayeredFuture +impl LayeredFuture where - S: Service>, + S: Service, { pub(super) fn new( - inner: Map>, fn(Result) -> Response>, + inner: Map, fn(Result) -> Response>, ) -> Self { Self { inner } } } -impl Future for LayeredFuture +impl Future for LayeredFuture where - S: Service>, + S: Service, { type Output = Response; diff --git a/axum/src/handler/mod.rs b/axum/src/handler/mod.rs index 338eea623c..d13701454d 100644 --- a/axum/src/handler/mod.rs +++ b/axum/src/handler/mod.rs @@ -37,12 +37,10 @@ #[cfg(feature = "tokio")] use crate::extract::connect_info::IntoMakeServiceWithConnectInfo; use crate::{ - body::Body, - extract::{FromRequest, FromRequestParts}, + extract::{FromRequest, FromRequestParts, Request}, response::{IntoResponse, Response}, routing::IntoMakeService, }; -use http::Request; use std::{convert::Infallible, fmt, future::Future, marker::PhantomData, pin::Pin}; use tower::ServiceExt; use tower_layer::Layer; @@ -68,9 +66,8 @@ pub use self::service::HandlerService; /// ``` /// use tower::Service; /// use axum::{ -/// extract::State, +/// extract::{State, Request}, /// body::Body, -/// http::Request, /// handler::{HandlerWithoutStateExt, Handler}, /// }; /// @@ -89,7 +86,7 @@ pub use self::service::HandlerService; /// // helper to check that a value implements `Service` /// fn assert_service(service: S) /// where -/// S: Service>, +/// S: Service, /// {} /// ``` #[doc = include_str!("../docs/debugging_handler_type_errors.md")] @@ -99,12 +96,12 @@ pub use self::service::HandlerService; note = "Consider using `#[axum::debug_handler]` to improve the error message" ) )] -pub trait Handler: Clone + Send + Sized + 'static { +pub trait Handler: Clone + Send + Sized + 'static { /// The type of future calling this handler returns. type Future: Future + Send + 'static; /// Call the handler with the given request. - fn call(self, req: Request, state: S) -> Self::Future; + fn call(self, req: Request, state: S) -> Self::Future; /// Apply a [`tower::Layer`] to the handler. /// @@ -138,14 +135,12 @@ pub trait Handler: Clone + Send + Sized + 'static { /// /// let layered_handler = handler.layer(ConcurrencyLimitLayer::new(64)); /// let app = Router::new().route("/", get(layered_handler)); - /// # async { - /// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); - /// # }; + /// # let _: Router = app; /// ``` - fn layer(self, layer: L) -> Layered + fn layer(self, layer: L) -> Layered where - L: Layer> + Clone, - L::Service: Service>, + L: Layer> + Clone, + L::Service: Service, { Layered { layer, @@ -155,21 +150,20 @@ pub trait Handler: Clone + Send + Sized + 'static { } /// Convert the handler into a [`Service`] by providing the state - fn with_state(self, state: S) -> HandlerService { + fn with_state(self, state: S) -> HandlerService { HandlerService::new(self, state) } } -impl Handler<((),), S, B> for F +impl Handler<((),), S> for F where F: FnOnce() -> Fut + Clone + Send + 'static, Fut: Future + Send, Res: IntoResponse, - B: Send + 'static, { type Future = Pin + Send>>; - fn call(self, _req: Request, _state: S) -> Self::Future { + fn call(self, _req: Request, _state: S) -> Self::Future { Box::pin(async move { self().await.into_response() }) } } @@ -179,19 +173,18 @@ macro_rules! impl_handler { [$($ty:ident),*], $last:ident ) => { #[allow(non_snake_case, unused_mut)] - impl Handler<(M, $($ty,)* $last,), S, B> for F + impl Handler<(M, $($ty,)* $last,), S> for F where F: FnOnce($($ty,)* $last,) -> Fut + Clone + Send + 'static, Fut: Future + Send, - B: Send + 'static, S: Send + Sync + 'static, Res: IntoResponse, $( $ty: FromRequestParts + Send, )* - $last: FromRequest + Send, + $last: FromRequest + Send, { type Future = Pin + Send>>; - fn call(self, req: Request, state: S) -> Self::Future { + fn call(self, req: Request, state: S) -> Self::Future { Box::pin(async move { let (mut parts, body) = req.into_parts(); let state = &state; @@ -224,13 +217,13 @@ all_the_tuples!(impl_handler); /// A [`Service`] created from a [`Handler`] by applying a Tower middleware. /// /// Created with [`Handler::layer`]. See that method for more details. -pub struct Layered { +pub struct Layered { layer: L, handler: H, - _marker: PhantomData (T, S, B, B2)>, + _marker: PhantomData (T, S)>, } -impl fmt::Debug for Layered +impl fmt::Debug for Layered where L: fmt::Debug, { @@ -241,7 +234,7 @@ where } } -impl Clone for Layered +impl Clone for Layered where L: Clone, H: Clone, @@ -255,21 +248,19 @@ where } } -impl Handler for Layered +impl Handler for Layered where - L: Layer> + Clone + Send + 'static, - H: Handler, - L::Service: Service, Error = Infallible> + Clone + Send + 'static, - >>::Response: IntoResponse, - >>::Future: Send, + L: Layer> + Clone + Send + 'static, + H: Handler, + L::Service: Service + Clone + Send + 'static, + >::Response: IntoResponse, + >::Future: Send, T: 'static, S: 'static, - B: Send + 'static, - B2: Send + 'static, { - type Future = future::LayeredFuture; + type Future = future::LayeredFuture; - fn call(self, req: Request, state: S) -> Self::Future { + fn call(self, req: Request, state: S) -> Self::Future { use futures_util::future::{FutureExt, Map}; let svc = self.handler.with_state(state); @@ -279,8 +270,8 @@ where _, fn( Result< - >>::Response, - >>::Error, + >::Response, + >::Error, >, ) -> _, > = svc.oneshot(req).map(|result| match result { @@ -297,16 +288,16 @@ where /// This provides convenience methods to convert the [`Handler`] into a [`Service`] or [`MakeService`]. /// /// [`MakeService`]: tower::make::MakeService -pub trait HandlerWithoutStateExt: Handler { +pub trait HandlerWithoutStateExt: Handler { /// Convert the handler into a [`Service`] and no state. - fn into_service(self) -> HandlerService; + fn into_service(self) -> HandlerService; /// Convert the handler into a [`MakeService`] and no state. /// /// See [`HandlerService::into_make_service`] for more details. /// /// [`MakeService`]: tower::make::MakeService - fn into_make_service(self) -> IntoMakeService>; + fn into_make_service(self) -> IntoMakeService>; /// Convert the handler into a [`MakeService`] which stores information /// about the incoming connection and has no state. @@ -317,25 +308,25 @@ pub trait HandlerWithoutStateExt: Handler { #[cfg(feature = "tokio")] fn into_make_service_with_connect_info( self, - ) -> IntoMakeServiceWithConnectInfo, C>; + ) -> IntoMakeServiceWithConnectInfo, C>; } -impl HandlerWithoutStateExt for H +impl HandlerWithoutStateExt for H where - H: Handler, + H: Handler, { - fn into_service(self) -> HandlerService { + fn into_service(self) -> HandlerService { self.with_state(()) } - fn into_make_service(self) -> IntoMakeService> { + fn into_make_service(self) -> IntoMakeService> { self.into_service().into_make_service() } #[cfg(feature = "tokio")] fn into_make_service_with_connect_info( self, - ) -> IntoMakeServiceWithConnectInfo, C> { + ) -> IntoMakeServiceWithConnectInfo, C> { self.into_service().into_make_service_with_connect_info() } } @@ -343,7 +334,8 @@ where #[cfg(test)] mod tests { use super::*; - use crate::{body, extract::State, test_helpers::*}; + use crate::{extract::State, test_helpers::*}; + use axum_core::body::Body; use http::StatusCode; use std::time::Duration; use tower_http::{ @@ -375,10 +367,10 @@ mod tests { .layer(( RequestBodyLimitLayer::new(1024), TimeoutLayer::new(Duration::from_secs(10)), - MapResponseBodyLayer::new(body::boxed), + MapResponseBodyLayer::new(Body::new), CompressionLayer::new(), )) - .layer(MapRequestBodyLayer::new(body::boxed)) + .layer(MapRequestBodyLayer::new(Body::new)) .with_state("foo"); let client = TestClient::new(svc); diff --git a/axum/src/handler/service.rs b/axum/src/handler/service.rs index 52fd5de67d..35974a4cda 100644 --- a/axum/src/handler/service.rs +++ b/axum/src/handler/service.rs @@ -1,8 +1,10 @@ use super::Handler; +use crate::body::{Body, Bytes, HttpBody}; #[cfg(feature = "tokio")] use crate::extract::connect_info::IntoMakeServiceWithConnectInfo; use crate::response::Response; use crate::routing::IntoMakeService; +use crate::BoxError; use http::Request; use std::{ convert::Infallible, @@ -17,13 +19,13 @@ use tower_service::Service; /// Created with [`Handler::with_state`] or [`HandlerWithoutStateExt::into_service`]. /// /// [`HandlerWithoutStateExt::into_service`]: super::HandlerWithoutStateExt::into_service -pub struct HandlerService { +pub struct HandlerService { handler: H, state: S, - _marker: PhantomData (T, B)>, + _marker: PhantomData T>, } -impl HandlerService { +impl HandlerService { /// Get a reference to the state. pub fn state(&self) -> &S { &self.state @@ -35,7 +37,6 @@ impl HandlerService { /// /// ```rust /// use axum::{ - /// Server, /// handler::Handler, /// extract::State, /// http::{Uri, Method}, @@ -53,15 +54,13 @@ impl HandlerService { /// let app = handler.with_state(AppState {}); /// /// # async { - /// Server::bind(&SocketAddr::from(([127, 0, 0, 1], 3000))) - /// .serve(app.into_make_service()) - /// .await?; - /// # Ok::<_, hyper::Error>(()) + /// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); + /// axum::serve(listener, app.into_make_service()).await.unwrap(); /// # }; /// ``` /// /// [`MakeService`]: tower::make::MakeService - pub fn into_make_service(self) -> IntoMakeService> { + pub fn into_make_service(self) -> IntoMakeService> { IntoMakeService::new(self) } @@ -72,7 +71,6 @@ impl HandlerService { /// /// ```rust /// use axum::{ - /// Server, /// handler::Handler, /// response::IntoResponse, /// extract::{ConnectInfo, State}, @@ -92,10 +90,11 @@ impl HandlerService { /// let app = handler.with_state(AppState {}); /// /// # async { - /// Server::bind(&SocketAddr::from(([127, 0, 0, 1], 3000))) - /// .serve(app.into_make_service_with_connect_info::()) - /// .await?; - /// # Ok::<_, hyper::Error>(()) + /// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); + /// axum::serve( + /// listener, + /// app.into_make_service_with_connect_info::(), + /// ).await.unwrap(); /// # }; /// ``` /// @@ -104,7 +103,7 @@ impl HandlerService { #[cfg(feature = "tokio")] pub fn into_make_service_with_connect_info( self, - ) -> IntoMakeServiceWithConnectInfo, C> { + ) -> IntoMakeServiceWithConnectInfo, C> { IntoMakeServiceWithConnectInfo::new(self) } } @@ -112,11 +111,11 @@ impl HandlerService { #[test] fn traits() { use crate::test_helpers::*; - assert_send::>(); - assert_sync::>(); + assert_send::>(); + assert_sync::>(); } -impl HandlerService { +impl HandlerService { pub(super) fn new(handler: H, state: S) -> Self { Self { handler, @@ -126,13 +125,13 @@ impl HandlerService { } } -impl fmt::Debug for HandlerService { +impl fmt::Debug for HandlerService { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("IntoService").finish_non_exhaustive() } } -impl Clone for HandlerService +impl Clone for HandlerService where H: Clone, S: Clone, @@ -146,10 +145,11 @@ where } } -impl Service> for HandlerService +impl Service> for HandlerService where - H: Handler + Clone + Send + 'static, - B: Send + 'static, + H: Handler + Clone + Send + 'static, + B: HttpBody + Send + 'static, + B::Error: Into, S: Clone + Send + Sync, { type Response = Response; @@ -167,6 +167,8 @@ where fn call(&mut self, req: Request) -> Self::Future { use futures_util::future::FutureExt; + let req = req.map(Body::new); + let handler = self.handler.clone(); let future = Handler::call(handler, req, self.state.clone()); let future = future.map(Ok as _); @@ -174,3 +176,27 @@ where super::future::IntoServiceFuture::new(future) } } + +// for `axum::serve(listener, handler)` +#[cfg(feature = "tokio")] +const _: () = { + use crate::serve::IncomingStream; + + impl Service> for HandlerService + where + H: Clone, + S: Clone, + { + type Response = Self; + type Error = Infallible; + type Future = std::future::Ready>; + + fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + + fn call(&mut self, _req: IncomingStream<'_>) -> Self::Future { + std::future::ready(Ok(self.clone())) + } + } +}; diff --git a/axum/src/json.rs b/axum/src/json.rs index 0f1775c8a9..a78f064496 100644 --- a/axum/src/json.rs +++ b/axum/src/json.rs @@ -1,14 +1,11 @@ -use crate::{ - body::{Bytes, HttpBody}, - extract::{rejection::*, FromRequest}, - BoxError, -}; +use crate::extract::Request; +use crate::extract::{rejection::*, FromRequest}; use async_trait::async_trait; use axum_core::response::{IntoResponse, Response}; -use bytes::{BufMut, BytesMut}; +use bytes::{BufMut, Bytes, BytesMut}; use http::{ header::{self, HeaderMap, HeaderValue}, - Request, StatusCode, + StatusCode, }; use serde::{de::DeserializeOwned, Serialize}; @@ -53,9 +50,7 @@ use serde::{de::DeserializeOwned, Serialize}; /// } /// /// let app = Router::new().route("/users", post(create_user)); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` /// /// When used as a response, it can serialize any type that implements [`serde::Serialize`] to @@ -90,9 +85,7 @@ use serde::{de::DeserializeOwned, Serialize}; /// } /// /// let app = Router::new().route("/users/:id", get(get_user)); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` #[derive(Debug, Clone, Copy, Default)] #[cfg_attr(docsrs, doc(cfg(feature = "json")))] @@ -100,17 +93,14 @@ use serde::{de::DeserializeOwned, Serialize}; pub struct Json(pub T); #[async_trait] -impl FromRequest for Json +impl FromRequest for Json where T: DeserializeOwned, - B: HttpBody + Send + 'static, - B::Data: Send, - B::Error: Into, S: Send + Sync, { type Rejection = JsonRejection; - async fn from_request(req: Request, state: &S) -> Result { + async fn from_request(req: Request, state: &S) -> Result { if json_content_type(req.headers()) { let bytes = Bytes::from_request(req, state).await?; let deserializer = &mut serde_json::Deserializer::from_slice(&bytes); diff --git a/axum/src/lib.rs b/axum/src/lib.rs index da60aef5ae..18f0b032c6 100644 --- a/axum/src/lib.rs +++ b/axum/src/lib.rs @@ -53,11 +53,9 @@ //! // build our application with a single route //! let app = Router::new().route("/", get(|| async { "Hello, World!" })); //! -//! // run it with hyper on localhost:3000 -//! axum::Server::bind(&"0.0.0.0:3000".parse().unwrap()) -//! .serve(app.into_make_service()) -//! .await -//! .unwrap(); +//! // run it on localhost:3000 +//! let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); +//! axum::serve(listener, app).await.unwrap(); //! } //! ``` //! @@ -82,9 +80,7 @@ //! async fn get_foo() {} //! async fn post_foo() {} //! async fn foo_bar() {} -//! # async { -//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -//! # }; +//! # let _: Router = app; //! ``` //! //! See [`Router`] for more details on routing. @@ -145,9 +141,7 @@ //! let app = Router::new() //! .route("/plain_text", get(plain_text)) //! .route("/json", get(json)); -//! # async { -//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -//! # }; +//! # let _: Router = app; //! ``` //! //! See [`response`](crate::response) for more details on building responses. @@ -202,9 +196,7 @@ //! ) { //! // ... //! } -//! # async { -//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -//! # }; +//! # let _: Router = app; //! ``` //! //! You should prefer using [`State`] if possible since it's more type safe. The downside is that @@ -240,9 +232,7 @@ //! ) { //! // ... //! } -//! # async { -//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -//! # }; +//! # let _: Router = app; //! ``` //! //! The downside to this approach is that you'll get runtime errors @@ -298,9 +288,7 @@ //! struct CreateUserPayload { //! // ... //! } -//! # async { -//! # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -//! # }; +//! # let _: Router = app; //! ``` //! //! The downside to this approach is that it's a little more verbose than using @@ -348,7 +336,6 @@ //! //! Name | Description | Default? //! ---|---|--- -//! `headers` | Enables extracting typed headers via [`TypedHeader`] | No //! `http1` | Enables hyper's `http1` feature | Yes //! `http2` | Enables hyper's `http2` feature | No //! `json` | Enables the [`Json`] type and some similar convenience functionality | Yes @@ -356,14 +343,13 @@ //! `matched-path` | Enables capturing of every request's router path and the [`MatchedPath`] extractor | Yes //! `multipart` | Enables parsing `multipart/form-data` requests with [`Multipart`] | No //! `original-uri` | Enables capturing of every request's original URI and the [`OriginalUri`] extractor | Yes -//! `tokio` | Enables `tokio` as a dependency and `axum::Server`, `SSE` and `extract::connect_info` types. | Yes +//! `tokio` | Enables `tokio` as a dependency and `axum::serve`, `SSE` and `extract::connect_info` types. | Yes //! `tower-log` | Enables `tower`'s `log` feature | Yes //! `tracing` | Log rejections from built-in extractors | No //! `ws` | Enables WebSockets support via [`extract::ws`] | No //! `form` | Enables the `Form` extractor | Yes //! `query` | Enables the `Query` extractor | Yes //! -//! [`TypedHeader`]: crate::extract::TypedHeader //! [`MatchedPath`]: crate::extract::MatchedPath //! [`Multipart`]: crate::extract::Multipart //! [`OriginalUri`]: crate::extract::OriginalUri @@ -377,7 +363,6 @@ //! [`Timeout`]: tower::timeout::Timeout //! [examples]: https://github.com/tokio-rs/axum/tree/main/examples //! [`Router::merge`]: crate::routing::Router::merge -//! [`axum::Server`]: hyper::server::Server //! [`Service`]: tower::Service //! [`Service::poll_ready`]: tower::Service::poll_ready //! [`Service`'s]: tower::Service @@ -448,8 +433,6 @@ mod form; #[cfg(feature = "json")] mod json; mod service_ext; -#[cfg(feature = "headers")] -mod typed_header; mod util; pub mod body; @@ -459,20 +442,16 @@ pub mod handler; pub mod middleware; pub mod response; pub mod routing; +#[cfg(feature = "tokio")] +pub mod serve; #[cfg(test)] mod test_helpers; #[doc(no_inline)] pub use async_trait::async_trait; -#[cfg(feature = "headers")] -#[doc(no_inline)] -pub use headers; #[doc(no_inline)] pub use http; -#[cfg(feature = "tokio")] -#[doc(no_inline)] -pub use hyper::Server; #[doc(inline)] pub use self::extension::Extension; @@ -482,10 +461,6 @@ pub use self::json::Json; #[doc(inline)] pub use self::routing::Router; -#[doc(inline)] -#[cfg(feature = "headers")] -pub use self::typed_header::TypedHeader; - #[doc(inline)] #[cfg(feature = "form")] pub use self::form::Form; @@ -496,6 +471,10 @@ pub use axum_core::{BoxError, Error, RequestExt, RequestPartsExt}; #[cfg(feature = "macros")] pub use axum_macros::debug_handler; +#[cfg(feature = "tokio")] +#[doc(inline)] +pub use self::serve::serve; + pub use self::service_ext::ServiceExt; #[cfg(test)] diff --git a/axum/src/middleware/from_extractor.rs b/axum/src/middleware/from_extractor.rs index 8c9a24833f..e120ffc1fc 100644 --- a/axum/src/middleware/from_extractor.rs +++ b/axum/src/middleware/from_extractor.rs @@ -84,9 +84,7 @@ use tower_service::Service; /// .route("/foo", post(other_handler)) /// // The extractor will run before all routes /// .route_layer(from_extractor::()); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` /// /// [`Bytes`]: bytes::Bytes diff --git a/axum/src/middleware/from_fn.rs b/axum/src/middleware/from_fn.rs index f380a580ad..b47a11a3e8 100644 --- a/axum/src/middleware/from_fn.rs +++ b/axum/src/middleware/from_fn.rs @@ -1,7 +1,6 @@ use crate::response::{IntoResponse, Response}; -use axum_core::extract::{FromRequest, FromRequestParts}; +use axum_core::extract::{FromRequest, FromRequestParts, Request}; use futures_util::future::BoxFuture; -use http::Request; use std::{ any::type_name, convert::Infallible, @@ -21,7 +20,7 @@ use tower_service::Service; /// /// 1. Be an `async fn`. /// 2. Take one or more [extractors] as the first arguments. -/// 3. Take [`Next`](Next) as the final argument. +/// 3. Take [`Next`](Next) as the final argument. /// 4. Return something that implements [`IntoResponse`]. /// /// Note that this function doesn't support extracting [`State`]. For that, use [`from_fn_with_state`]. @@ -31,15 +30,16 @@ use tower_service::Service; /// ```rust /// use axum::{ /// Router, -/// http::{self, Request}, +/// http, /// routing::get, /// response::Response, /// middleware::{self, Next}, +/// extract::Request, /// }; /// -/// async fn my_middleware( -/// request: Request, -/// next: Next, +/// async fn my_middleware( +/// request: Request, +/// next: Next, /// ) -> Response { /// // do something with `request`... /// @@ -61,32 +61,38 @@ use tower_service::Service; /// ```rust /// use axum::{ /// Router, -/// extract::TypedHeader, -/// http::StatusCode, -/// headers::authorization::{Authorization, Bearer}, -/// http::Request, +/// extract::Request, +/// http::{StatusCode, HeaderMap}, /// middleware::{self, Next}, /// response::Response, /// routing::get, /// }; /// -/// async fn auth( -/// // run the `TypedHeader` extractor -/// TypedHeader(auth): TypedHeader>, +/// async fn auth( +/// // run the `HeaderMap` extractor +/// headers: HeaderMap, /// // you can also add more extractors here but the last /// // extractor must implement `FromRequest` which /// // `Request` does -/// request: Request, -/// next: Next, +/// request: Request, +/// next: Next, /// ) -> Result { -/// if token_is_valid(auth.token()) { -/// let response = next.run(request).await; -/// Ok(response) -/// } else { -/// Err(StatusCode::UNAUTHORIZED) +/// match get_token(&headers) { +/// Some(token) if token_is_valid(token) => { +/// let response = next.run(request).await; +/// Ok(response) +/// } +/// _ => { +/// Err(StatusCode::UNAUTHORIZED) +/// } /// } /// } /// +/// fn get_token(headers: &HeaderMap) -> Option<&str> { +/// // ... +/// # None +/// } +/// /// fn token_is_valid(token: &str) -> bool { /// // ... /// # false @@ -113,23 +119,23 @@ pub fn from_fn(f: F) -> FromFnLayer { /// ```rust /// use axum::{ /// Router, -/// http::{Request, StatusCode}, +/// http::StatusCode, /// routing::get, /// response::{IntoResponse, Response}, /// middleware::{self, Next}, -/// extract::State, +/// extract::{Request, State}, /// }; /// /// #[derive(Clone)] /// struct AppState { /* ... */ } /// -/// async fn my_middleware( +/// async fn my_middleware( /// State(state): State, /// // you can add more extractors here but the last /// // extractor must implement `FromRequest` which /// // `Request` does -/// request: Request, -/// next: Next, +/// request: Request, +/// next: Next, /// ) -> Response { /// // do something with `request`... /// @@ -243,20 +249,19 @@ macro_rules! impl_service { [$($ty:ident),*], $last:ident ) => { #[allow(non_snake_case, unused_mut)] - impl Service> for FromFn + impl Service for FromFn where - F: FnMut($($ty,)* $last, Next) -> Fut + Clone + Send + 'static, + F: FnMut($($ty,)* $last, Next) -> Fut + Clone + Send + 'static, $( $ty: FromRequestParts + Send, )* - $last: FromRequest + Send, + $last: FromRequest + Send, Fut: Future + Send + 'static, Out: IntoResponse + 'static, - I: Service, Error = Infallible> + I: Service + Clone + Send + 'static, I::Response: IntoResponse, I::Future: Send + 'static, - B: Send + 'static, S: Clone + Send + Sync + 'static, { type Response = Response; @@ -267,7 +272,7 @@ macro_rules! impl_service { self.inner.poll_ready(cx) } - fn call(&mut self, req: Request) -> Self::Future { + fn call(&mut self, req: Request) -> Self::Future { let not_ready_inner = self.inner.clone(); let ready_inner = std::mem::replace(&mut self.inner, not_ready_inner); @@ -325,13 +330,14 @@ where } /// The remainder of a middleware stack, including the handler. -pub struct Next { - inner: BoxCloneService, Response, Infallible>, +#[derive(Debug, Clone)] +pub struct Next { + inner: BoxCloneService, } -impl Next { +impl Next { /// Execute the remaining middleware stack. - pub async fn run(mut self, req: Request) -> Response { + pub async fn run(mut self, req: Request) -> Response { match self.inner.call(req).await { Ok(res) => res, Err(err) => match err {}, @@ -339,23 +345,7 @@ impl Next { } } -impl fmt::Debug for Next { - fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { - f.debug_struct("FromFnLayer") - .field("inner", &self.inner) - .finish() - } -} - -impl Clone for Next { - fn clone(&self) -> Self { - Self { - inner: self.inner.clone(), - } - } -} - -impl Service> for Next { +impl Service for Next { type Response = Response; type Error = Infallible; type Future = Pin> + Send>>; @@ -364,7 +354,7 @@ impl Service> for Next { self.inner.poll_ready(cx) } - fn call(&mut self, req: Request) -> Self::Future { + fn call(&mut self, req: Request) -> Self::Future { self.inner.call(req) } } @@ -397,7 +387,7 @@ mod tests { #[crate::test] async fn basic() { - async fn insert_header(mut req: Request, next: Next) -> impl IntoResponse { + async fn insert_header(mut req: Request, next: Next) -> impl IntoResponse { req.headers_mut() .insert("x-axum-test", "ok".parse().unwrap()); diff --git a/axum/src/middleware/map_request.rs b/axum/src/middleware/map_request.rs index 5d1801ac7c..d36a7cc958 100644 --- a/axum/src/middleware/map_request.rs +++ b/axum/src/middleware/map_request.rs @@ -1,4 +1,6 @@ +use crate::body::{Body, Bytes, HttpBody}; use crate::response::{IntoResponse, Response}; +use crate::BoxError; use axum_core::extract::{FromRequest, FromRequestParts}; use futures_util::future::BoxFuture; use http::Request; @@ -251,7 +253,7 @@ macro_rules! impl_service { where F: FnMut($($ty,)* $last) -> Fut + Clone + Send + 'static, $( $ty: FromRequestParts + Send, )* - $last: FromRequest + Send, + $last: FromRequest + Send, Fut: Future + Send + 'static, Fut::Output: IntoMapRequestResult + Send + 'static, I: Service, Error = Infallible> @@ -260,7 +262,8 @@ macro_rules! impl_service { + 'static, I::Response: IntoResponse, I::Future: Send + 'static, - B: Send + 'static, + B: HttpBody + Send + 'static, + B::Error: Into, S: Clone + Send + Sync + 'static, { type Response = Response; @@ -272,6 +275,8 @@ macro_rules! impl_service { } fn call(&mut self, req: Request) -> Self::Future { + let req = req.map(Body::new); + let not_ready_inner = self.inner.clone(); let mut ready_inner = std::mem::replace(&mut self.inner, not_ready_inner); diff --git a/axum/src/response/mod.rs b/axum/src/response/mod.rs index 2c149748a6..6cfd9b0763 100644 --- a/axum/src/response/mod.rs +++ b/axum/src/response/mod.rs @@ -1,6 +1,6 @@ #![doc = include_str!("../docs/response.md")] -use crate::body::{Bytes, Full}; +use axum_core::body::Body; use http::{header, HeaderValue}; mod redirect; @@ -12,10 +12,6 @@ pub mod sse; #[cfg(feature = "json")] pub use crate::Json; -#[doc(no_inline)] -#[cfg(feature = "headers")] -pub use crate::TypedHeader; - #[cfg(feature = "form")] #[doc(no_inline)] pub use crate::form::Form; @@ -44,7 +40,7 @@ pub struct Html(pub T); impl IntoResponse for Html where - T: Into>, + T: Into, { fn into_response(self) -> Response { ( @@ -67,7 +63,7 @@ impl From for Html { #[cfg(test)] mod tests { use crate::extract::Extension; - use crate::{body::Body, routing::get, Router}; + use crate::{routing::get, Router}; use axum_core::response::IntoResponse; use http::HeaderMap; use http::{StatusCode, Uri}; @@ -99,7 +95,7 @@ mod tests { } } - _ = Router::<(), Body>::new() + _ = Router::<()>::new() .route("/", get(impl_trait_ok)) .route("/", get(impl_trait_err)) .route("/", get(impl_trait_both)) @@ -209,7 +205,7 @@ mod tests { ) } - _ = Router::<(), Body>::new() + _ = Router::<()>::new() .route("/", get(status)) .route("/", get(status_headermap)) .route("/", get(status_header_array)) diff --git a/axum/src/response/sse.rs b/axum/src/response/sse.rs index 2e9e28535e..3f849b9278 100644 --- a/axum/src/response/sse.rs +++ b/axum/src/response/sse.rs @@ -32,7 +32,7 @@ use crate::{ BoxError, }; use axum_core::{ - body, + body::Body, response::{IntoResponse, Response}, }; use bytes::{BufMut, BytesMut}; @@ -104,7 +104,7 @@ where (http::header::CONTENT_TYPE, mime::TEXT_EVENT_STREAM.as_ref()), (http::header::CACHE_CONTROL, "no-cache"), ], - body::boxed(Body { + Body::new(SseBody { event_stream: SyncWrapper::new(self.stream), keep_alive: self.keep_alive.map(KeepAliveStream::new), }), @@ -114,7 +114,7 @@ where } pin_project! { - struct Body { + struct SseBody { #[pin] event_stream: SyncWrapper, #[pin] @@ -122,7 +122,7 @@ pin_project! { } } -impl HttpBody for Body +impl HttpBody for SseBody where S: Stream>, { @@ -212,7 +212,7 @@ impl Event { /// /// [`MessageEvent`'s data field]: https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent/data #[cfg(feature = "json")] - pub fn json_data(mut self, data: T) -> serde_json::Result + pub fn json_data(mut self, data: T) -> Result where T: serde::Serialize, { @@ -221,7 +221,7 @@ impl Event { } self.buffer.extend_from_slice(b"data:"); - serde_json::to_writer((&mut self.buffer).writer(), &data)?; + serde_json::to_writer((&mut self.buffer).writer(), &data).map_err(axum_core::Error::new)?; self.buffer.put_u8(b'\n'); self.flags.insert(EventFlags::HAS_DATA); diff --git a/axum/src/routing/into_make_service.rs b/axum/src/routing/into_make_service.rs index fbc57c4acc..36da73a21e 100644 --- a/axum/src/routing/into_make_service.rs +++ b/axum/src/routing/into_make_service.rs @@ -46,12 +46,11 @@ opaque_future! { #[cfg(test)] mod tests { use super::*; - use crate::body::Body; #[test] fn traits() { use crate::test_helpers::*; - assert_send::>(); + assert_send::>(); } } diff --git a/axum/src/routing/method_routing.rs b/axum/src/routing/method_routing.rs index cd94290227..dc8f9ec019 100644 --- a/axum/src/routing/method_routing.rs +++ b/axum/src/routing/method_routing.rs @@ -8,11 +8,11 @@ use crate::{ boxed::BoxedIntoRoute, error_handling::{HandleError, HandleErrorLayer}, handler::Handler, - http::{Method, Request, StatusCode}, + http::{Method, StatusCode}, response::Response, routing::{future::RouteFuture, Fallback, MethodFilter, Route}, }; -use axum_core::response::IntoResponse; +use axum_core::{extract::Request, response::IntoResponse, BoxError}; use bytes::BytesMut; use std::{ convert::Infallible, @@ -34,23 +34,21 @@ macro_rules! top_level_service_fn { /// /// ```rust /// use axum::{ - /// http::Request, + /// extract::Request, /// Router, /// routing::get_service, + /// body::Body, /// }; /// use http::Response; /// use std::convert::Infallible; - /// use hyper::Body; /// - /// let service = tower::service_fn(|request: Request| async { + /// let service = tower::service_fn(|request: Request| async { /// Ok::<_, Infallible>(Response::new(Body::empty())) /// }); /// /// // Requests to `GET /` will go to `service`. /// let app = Router::new().route("/", get_service(service)); - /// # async { - /// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); - /// # }; + /// # let _: Router = app; /// ``` /// /// Note that `get` routes will also be called for `HEAD` requests but will have @@ -78,12 +76,11 @@ macro_rules! top_level_service_fn { $name:ident, $method:ident ) => { $(#[$m])+ - pub fn $name(svc: T) -> MethodRouter + pub fn $name(svc: T) -> MethodRouter where - T: Service> + Clone + Send + 'static, + T: Service + Clone + Send + 'static, T::Response: IntoResponse + 'static, T::Future: Send + 'static, - B: HttpBody + Send + 'static, S: Clone, { on_service(MethodFilter::$method, svc) @@ -110,9 +107,7 @@ macro_rules! top_level_handler_fn { /// /// // Requests to `GET /` will go to `handler`. /// let app = Router::new().route("/", get(handler)); - /// # async { - /// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); - /// # }; + /// # let _: Router = app; /// ``` /// /// Note that `get` routes will also be called for `HEAD` requests but will have @@ -140,10 +135,9 @@ macro_rules! top_level_handler_fn { $name:ident, $method:ident ) => { $(#[$m])+ - pub fn $name(handler: H) -> MethodRouter + pub fn $name(handler: H) -> MethodRouter where - H: Handler, - B: HttpBody + Send + 'static, + H: Handler, T: 'static, S: Clone + Send + Sync + 'static, { @@ -163,28 +157,26 @@ macro_rules! chained_service_fn { /// /// ```rust /// use axum::{ - /// http::Request, + /// extract::Request, /// Router, /// routing::post_service, + /// body::Body, /// }; /// use http::Response; /// use std::convert::Infallible; - /// use hyper::Body; /// - /// let service = tower::service_fn(|request: Request| async { + /// let service = tower::service_fn(|request: Request| async { /// Ok::<_, Infallible>(Response::new(Body::empty())) /// }); /// - /// let other_service = tower::service_fn(|request: Request| async { + /// let other_service = tower::service_fn(|request: Request| async { /// Ok::<_, Infallible>(Response::new(Body::empty())) /// }); /// /// // Requests to `POST /` will go to `service` and `GET /` will go to /// // `other_service`. /// let app = Router::new().route("/", post_service(service).get_service(other_service)); - /// # async { - /// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); - /// # }; + /// # let _: Router = app; /// ``` /// /// Note that `get` routes will also be called for `HEAD` requests but will have @@ -215,7 +207,7 @@ macro_rules! chained_service_fn { #[track_caller] pub fn $name(self, svc: T) -> Self where - T: Service, Error = E> + T: Service + Clone + Send + 'static, @@ -246,9 +238,7 @@ macro_rules! chained_handler_fn { /// // Requests to `POST /` will go to `handler` and `GET /` will go to /// // `other_handler`. /// let app = Router::new().route("/", post(handler).get(other_handler)); - /// # async { - /// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); - /// # }; + /// # let _: Router = app; /// ``` /// /// Note that `get` routes will also be called for `HEAD` requests but will have @@ -279,7 +269,7 @@ macro_rules! chained_handler_fn { #[track_caller] pub fn $name(self, handler: H) -> Self where - H: Handler, + H: Handler, T: 'static, S: Send + Sync + 'static, { @@ -303,31 +293,28 @@ top_level_service_fn!(trace_service, TRACE); /// /// ```rust /// use axum::{ -/// http::Request, +/// extract::Request, /// routing::on, /// Router, +/// body::Body, /// routing::{MethodFilter, on_service}, /// }; /// use http::Response; /// use std::convert::Infallible; -/// use hyper::Body; /// -/// let service = tower::service_fn(|request: Request| async { +/// let service = tower::service_fn(|request: Request| async { /// Ok::<_, Infallible>(Response::new(Body::empty())) /// }); /// /// // Requests to `POST /` will go to `service`. /// let app = Router::new().route("/", on_service(MethodFilter::POST, service)); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` -pub fn on_service(filter: MethodFilter, svc: T) -> MethodRouter +pub fn on_service(filter: MethodFilter, svc: T) -> MethodRouter where - T: Service> + Clone + Send + 'static, + T: Service + Clone + Send + 'static, T::Response: IntoResponse + 'static, T::Future: Send + 'static, - B: HttpBody + Send + 'static, S: Clone, { MethodRouter::new().on_service(filter, svc) @@ -339,59 +326,54 @@ where /// /// ```rust /// use axum::{ -/// http::Request, +/// extract::Request, /// Router, /// routing::any_service, +/// body::Body, /// }; /// use http::Response; /// use std::convert::Infallible; -/// use hyper::Body; /// -/// let service = tower::service_fn(|request: Request| async { +/// let service = tower::service_fn(|request: Request| async { /// Ok::<_, Infallible>(Response::new(Body::empty())) /// }); /// /// // All requests to `/` will go to `service`. /// let app = Router::new().route("/", any_service(service)); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` /// /// Additional methods can still be chained: /// /// ```rust /// use axum::{ -/// http::Request, +/// extract::Request, /// Router, /// routing::any_service, +/// body::Body, /// }; /// use http::Response; /// use std::convert::Infallible; -/// use hyper::Body; /// -/// let service = tower::service_fn(|request: Request| async { +/// let service = tower::service_fn(|request: Request| async { /// # Ok::<_, Infallible>(Response::new(Body::empty())) /// // ... /// }); /// -/// let other_service = tower::service_fn(|request: Request| async { +/// let other_service = tower::service_fn(|request: Request| async { /// # Ok::<_, Infallible>(Response::new(Body::empty())) /// // ... /// }); /// /// // `POST /` goes to `other_service`. All other requests go to `service` /// let app = Router::new().route("/", any_service(service).post_service(other_service)); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` -pub fn any_service(svc: T) -> MethodRouter +pub fn any_service(svc: T) -> MethodRouter where - T: Service> + Clone + Send + 'static, + T: Service + Clone + Send + 'static, T::Response: IntoResponse + 'static, T::Future: Send + 'static, - B: HttpBody + Send + 'static, S: Clone, { MethodRouter::new() @@ -423,14 +405,11 @@ top_level_handler_fn!(trace, TRACE); /// /// // Requests to `POST /` will go to `handler`. /// let app = Router::new().route("/", on(MethodFilter::POST, handler)); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` -pub fn on(filter: MethodFilter, handler: H) -> MethodRouter +pub fn on(filter: MethodFilter, handler: H) -> MethodRouter where - H: Handler, - B: HttpBody + Send + 'static, + H: Handler, T: 'static, S: Clone + Send + Sync + 'static, { @@ -451,9 +430,7 @@ where /// /// // All requests to `/` will go to `handler`. /// let app = Router::new().route("/", any(handler)); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` /// /// Additional methods can still be chained: @@ -470,14 +447,11 @@ where /// /// // `POST /` goes to `other_handler`. All other requests go to `handler` /// let app = Router::new().route("/", any(handler).post(other_handler)); -/// # async { -/// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); -/// # }; +/// # let _: Router = app; /// ``` -pub fn any(handler: H) -> MethodRouter +pub fn any(handler: H) -> MethodRouter where - H: Handler, - B: HttpBody + Send + 'static, + H: Handler, T: 'static, S: Clone + Send + Sync + 'static, { @@ -493,7 +467,7 @@ where /// /// ``` /// use tower::Service; -/// use axum::{routing::get, extract::State, body::Body, http::Request}; +/// use axum::{routing::get, extract::{State, Request}, body::Body}; /// /// // this `MethodRouter` doesn't require any state, i.e. the state is `()`, /// let method_router = get(|| async {}); @@ -510,20 +484,20 @@ where /// // helper to check that a value implements `Service` /// fn assert_service(service: S) /// where -/// S: Service>, +/// S: Service, /// {} /// ``` #[must_use] -pub struct MethodRouter { - get: MethodEndpoint, - head: MethodEndpoint, - delete: MethodEndpoint, - options: MethodEndpoint, - patch: MethodEndpoint, - post: MethodEndpoint, - put: MethodEndpoint, - trace: MethodEndpoint, - fallback: Fallback, +pub struct MethodRouter { + get: MethodEndpoint, + head: MethodEndpoint, + delete: MethodEndpoint, + options: MethodEndpoint, + patch: MethodEndpoint, + post: MethodEndpoint, + put: MethodEndpoint, + trace: MethodEndpoint, + fallback: Fallback, allow_header: AllowHeader, } @@ -553,7 +527,7 @@ impl AllowHeader { } } -impl fmt::Debug for MethodRouter { +impl fmt::Debug for MethodRouter { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("MethodRouter") .field("get", &self.get) @@ -570,9 +544,8 @@ impl fmt::Debug for MethodRouter { } } -impl MethodRouter +impl MethodRouter where - B: HttpBody + Send + 'static, S: Clone, { /// Chain an additional handler that will accept requests matching the given @@ -594,14 +567,12 @@ where /// // Requests to `GET /` will go to `handler` and `DELETE /` will go to /// // `other_handler` /// let app = Router::new().route("/", get(handler).on(MethodFilter::DELETE, other_handler)); - /// # async { - /// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); - /// # }; + /// # let _: Router = app; /// ``` #[track_caller] pub fn on(self, filter: MethodFilter, handler: H) -> Self where - H: Handler, + H: Handler, T: 'static, S: Send + Sync + 'static, { @@ -623,7 +594,7 @@ where /// Add a fallback [`Handler`] to the router. pub fn fallback(mut self, handler: H) -> Self where - H: Handler, + H: Handler, T: 'static, S: Send + Sync + 'static, { @@ -632,17 +603,13 @@ where } } -impl MethodRouter<(), B, Infallible> -where - B: HttpBody + Send + 'static, -{ +impl MethodRouter<(), Infallible> { /// Convert the handler into a [`MakeService`]. /// /// This allows you to serve a single handler if you don't need any routing: /// /// ```rust /// use axum::{ - /// Server, /// handler::Handler, /// http::{Uri, Method}, /// response::IntoResponse, @@ -657,10 +624,8 @@ where /// let router = get(handler).post(handler); /// /// # async { - /// Server::bind(&SocketAddr::from(([127, 0, 0, 1], 3000))) - /// .serve(router.into_make_service()) - /// .await?; - /// # Ok::<_, hyper::Error>(()) + /// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); + /// axum::serve(listener, router.into_make_service()).await.unwrap(); /// # }; /// ``` /// @@ -676,7 +641,6 @@ where /// /// ```rust /// use axum::{ - /// Server, /// handler::Handler, /// response::IntoResponse, /// extract::ConnectInfo, @@ -691,10 +655,8 @@ where /// let router = get(handler).post(handler); /// /// # async { - /// Server::bind(&SocketAddr::from(([127, 0, 0, 1], 3000))) - /// .serve(router.into_make_service_with_connect_info::()) - /// .await?; - /// # Ok::<_, hyper::Error>(()) + /// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); + /// axum::serve(listener, router.into_make_service()).await.unwrap(); /// # }; /// ``` /// @@ -706,15 +668,14 @@ where } } -impl MethodRouter +impl MethodRouter where - B: HttpBody + Send + 'static, S: Clone, { /// Create a default `MethodRouter` that will respond with `405 Method Not Allowed` to all /// requests. pub fn new() -> Self { - let fallback = Route::new(service_fn(|_: Request| async { + let fallback = Route::new(service_fn(|_: Request| async { Ok(StatusCode::METHOD_NOT_ALLOWED.into_response()) })); @@ -733,7 +694,7 @@ where } /// Provide the state for the router. - pub fn with_state(self, state: S) -> MethodRouter { + pub fn with_state(self, state: S) -> MethodRouter { MethodRouter { get: self.get.with_state(&state), head: self.head.with_state(&state), @@ -755,28 +716,26 @@ where /// /// ```rust /// use axum::{ - /// http::Request, + /// extract::Request, /// Router, /// routing::{MethodFilter, on_service}, + /// body::Body, /// }; /// use http::Response; /// use std::convert::Infallible; - /// use hyper::Body; /// - /// let service = tower::service_fn(|request: Request| async { + /// let service = tower::service_fn(|request: Request| async { /// Ok::<_, Infallible>(Response::new(Body::empty())) /// }); /// /// // Requests to `DELETE /` will go to `service` /// let app = Router::new().route("/", on_service(MethodFilter::DELETE, service)); - /// # async { - /// # axum::Server::bind(&"".parse().unwrap()).serve(app.into_make_service()).await.unwrap(); - /// # }; + /// # let _: Router = app; /// ``` #[track_caller] pub fn on_service(self, filter: MethodFilter, svc: T) -> Self where - T: Service, Error = E> + Clone + Send + 'static, + T: Service + Clone + Send + 'static, T::Response: IntoResponse + 'static, T::Future: Send + 'static, { @@ -784,19 +743,19 @@ where } #[track_caller] - fn on_endpoint(mut self, filter: MethodFilter, endpoint: MethodEndpoint) -> Self { + fn on_endpoint(mut self, filter: MethodFilter, endpoint: MethodEndpoint) -> Self { // written as a separate function to generate less IR #[track_caller] - fn set_endpoint( + fn set_endpoint( method_name: &str, - out: &mut MethodEndpoint, - endpoint: &MethodEndpoint, + out: &mut MethodEndpoint, + endpoint: &MethodEndpoint, endpoint_filter: MethodFilter, filter: MethodFilter, allow_header: &mut AllowHeader, methods: &[&'static str], ) where - MethodEndpoint: Clone, + MethodEndpoint: Clone, S: Clone, { if endpoint_filter.contains(filter) { @@ -908,7 +867,7 @@ where #[doc = include_str!("../docs/method_routing/fallback.md")] pub fn fallback_service(mut self, svc: T) -> Self where - T: Service, Error = E> + Clone + Send + 'static, + T: Service + Clone + Send + 'static, T::Response: IntoResponse + 'static, T::Future: Send + 'static, { @@ -917,19 +876,18 @@ where } #[doc = include_str!("../docs/method_routing/layer.md")] - pub fn layer(self, layer: L) -> MethodRouter + pub fn layer(self, layer: L) -> MethodRouter where - L: Layer> + Clone + Send + 'static, - L::Service: Service> + Clone + Send + 'static, - >>::Response: IntoResponse + 'static, - >>::Error: Into + 'static, - >>::Future: Send + 'static, + L: Layer> + Clone + Send + 'static, + L::Service: Service + Clone + Send + 'static, + >::Response: IntoResponse + 'static, + >::Error: Into + 'static, + >::Future: Send + 'static, E: 'static, S: 'static, - NewReqBody: HttpBody + 'static, NewError: 'static, { - let layer_fn = move |route: Route| route.layer(layer.clone()); + let layer_fn = move |route: Route| route.layer(layer.clone()); MethodRouter { get: self.get.map(layer_fn.clone()), @@ -947,12 +905,12 @@ where #[doc = include_str!("../docs/method_routing/route_layer.md")] #[track_caller] - pub fn route_layer(mut self, layer: L) -> MethodRouter + pub fn route_layer(mut self, layer: L) -> MethodRouter where - L: Layer> + Clone + Send + 'static, - L::Service: Service, Error = E> + Clone + Send + 'static, - >>::Response: IntoResponse + 'static, - >>::Future: Send + 'static, + L: Layer> + Clone + Send + 'static, + L::Service: Service + Clone + Send + 'static, + >::Response: IntoResponse + 'static, + >::Future: Send + 'static, E: 'static, S: 'static, { @@ -990,19 +948,15 @@ where } #[track_caller] - pub(crate) fn merge_for_path( - mut self, - path: Option<&str>, - other: MethodRouter, - ) -> Self { + pub(crate) fn merge_for_path(mut self, path: Option<&str>, other: MethodRouter) -> Self { // written using inner functions to generate less IR #[track_caller] - fn merge_inner( + fn merge_inner( path: Option<&str>, name: &str, - first: MethodEndpoint, - second: MethodEndpoint, - ) -> MethodEndpoint { + first: MethodEndpoint, + second: MethodEndpoint, + ) -> MethodEndpoint { match (first, second) { (MethodEndpoint::None, MethodEndpoint::None) => MethodEndpoint::None, (pick, MethodEndpoint::None) | (MethodEndpoint::None, pick) => pick, @@ -1042,22 +996,21 @@ where #[doc = include_str!("../docs/method_routing/merge.md")] #[track_caller] - pub fn merge(self, other: MethodRouter) -> Self { + pub fn merge(self, other: MethodRouter) -> Self { self.merge_for_path(None, other) } /// Apply a [`HandleErrorLayer`]. /// /// This is a convenience method for doing `self.layer(HandleErrorLayer::new(f))`. - pub fn handle_error(self, f: F) -> MethodRouter + pub fn handle_error(self, f: F) -> MethodRouter where F: Clone + Send + Sync + 'static, - HandleError, F, T>: Service, Error = Infallible>, - , F, T> as Service>>::Future: Send, - , F, T> as Service>>::Response: IntoResponse + Send, + HandleError, F, T>: Service, + , F, T> as Service>::Future: Send, + , F, T> as Service>::Response: IntoResponse + Send, T: 'static, E: 'static, - B: 'static, S: 'static, { self.layer(HandleErrorLayer::new(f)) @@ -1068,7 +1021,7 @@ where self } - pub(crate) fn call_with_state(&mut self, req: Request, state: S) -> RouteFuture { + pub(crate) fn call_with_state(&mut self, req: Request, state: S) -> RouteFuture { macro_rules! call { ( $req:expr, @@ -1157,7 +1110,7 @@ fn append_allow_header(allow_header: &mut AllowHeader, method: &'static str) { } } -impl Clone for MethodRouter { +impl Clone for MethodRouter { fn clone(&self) -> Self { Self { get: self.get.clone(), @@ -1174,9 +1127,8 @@ impl Clone for MethodRouter { } } -impl Default for MethodRouter +impl Default for MethodRouter where - B: HttpBody + Send + 'static, S: Clone, { fn default() -> Self { @@ -1184,13 +1136,13 @@ where } } -enum MethodEndpoint { +enum MethodEndpoint { None, - Route(Route), - BoxedHandler(BoxedIntoRoute), + Route(Route), + BoxedHandler(BoxedIntoRoute), } -impl MethodEndpoint +impl MethodEndpoint where S: Clone, { @@ -1202,13 +1154,11 @@ where matches!(self, Self::None) } - fn map(self, f: F) -> MethodEndpoint + fn map(self, f: F) -> MethodEndpoint where S: 'static, - B: 'static, E: 'static, - F: FnOnce(Route) -> Route + Clone + Send + 'static, - B2: HttpBody + 'static, + F: FnOnce(Route) -> Route + Clone + Send + 'static, E2: 'static, { match self { @@ -1218,7 +1168,7 @@ where } } - fn with_state(self, state: &S) -> MethodEndpoint { + fn with_state(self, state: &S) -> MethodEndpoint { match self { MethodEndpoint::None => MethodEndpoint::None, MethodEndpoint::Route(route) => MethodEndpoint::Route(route), @@ -1229,7 +1179,7 @@ where } } -impl Clone for MethodEndpoint { +impl Clone for MethodEndpoint { fn clone(&self) -> Self { match self { Self::None => Self::None, @@ -1239,7 +1189,7 @@ impl Clone for MethodEndpoint { } } -impl fmt::Debug for MethodEndpoint { +impl fmt::Debug for MethodEndpoint { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::None => f.debug_tuple("None").finish(), @@ -1249,13 +1199,14 @@ impl fmt::Debug for MethodEndpoint { } } -impl Service> for MethodRouter<(), B, E> +impl Service> for MethodRouter<(), E> where - B: HttpBody + Send + 'static, + B: HttpBody + Send + 'static, + B::Error: Into, { type Response = Response; type Error = E; - type Future = RouteFuture; + type Future = RouteFuture; #[inline] fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { @@ -1264,22 +1215,42 @@ where #[inline] fn call(&mut self, req: Request) -> Self::Future { + let req = req.map(Body::new); self.call_with_state(req, ()) } } -impl Handler<(), S, B> for MethodRouter +impl Handler<(), S> for MethodRouter where S: Clone + 'static, - B: HttpBody + Send + 'static, { - type Future = InfallibleRouteFuture; + type Future = InfallibleRouteFuture; - fn call(mut self, req: Request, state: S) -> Self::Future { + fn call(mut self, req: Request, state: S) -> Self::Future { InfallibleRouteFuture::new(self.call_with_state(req, state)) } } +// for `axum::serve(listener, router)` +#[cfg(feature = "tokio")] +const _: () = { + use crate::serve::IncomingStream; + + impl Service> for MethodRouter<()> { + type Response = Self; + type Error = Infallible; + type Future = std::future::Ready>; + + fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + + fn call(&mut self, _req: IncomingStream<'_>) -> Self::Future { + std::future::ready(Ok(self.clone())) + } + } +}; + #[cfg(test)] mod tests { use super::*; @@ -1303,7 +1274,7 @@ mod tests { #[crate::test] async fn get_service_fn() { - async fn handle(_req: Request) -> Result, Infallible> { + async fn handle(_req: Request) -> Result, Infallible> { Ok(Response::new(Body::from("ok"))) } @@ -1380,7 +1351,7 @@ mod tests { } #[allow(dead_code)] - fn buiding_complex_router() { + async fn buiding_complex_router() { let app = crate::Router::new().route( "/", // use the all the things :bomb: @@ -1399,7 +1370,8 @@ mod tests { ), ); - crate::Server::bind(&"0.0.0.0:0".parse().unwrap()).serve(app.into_make_service()); + let listener = tokio::net::TcpListener::bind("0.0.0.0:0").await.unwrap(); + crate::serve(listener, app).await.unwrap(); } #[crate::test] @@ -1564,7 +1536,7 @@ mod tests { async fn call(method: Method, svc: &mut S) -> (StatusCode, HeaderMap, String) where - S: Service, Error = Infallible>, + S: Service, S::Response: IntoResponse, { let request = Request::builder() diff --git a/axum/src/routing/mod.rs b/axum/src/routing/mod.rs index a1d8c715d9..12b66ac6e7 100644 --- a/axum/src/routing/mod.rs +++ b/axum/src/routing/mod.rs @@ -9,11 +9,14 @@ use crate::{ handler::Handler, util::try_downcast, }; -use axum_core::response::{IntoResponse, Response}; -use http::Request; +use axum_core::{ + extract::Request, + response::{IntoResponse, Response}, +}; use std::{ convert::Infallible, fmt, + marker::PhantomData, task::{Context, Poll}, }; use sync_wrapper::SyncWrapper; @@ -56,13 +59,13 @@ pub(crate) struct RouteId(u32); /// The router type for composing handlers and services. #[must_use] -pub struct Router { - path_router: PathRouter, - fallback_router: PathRouter, +pub struct Router { + path_router: PathRouter, + fallback_router: PathRouter, default_fallback: bool, } -impl Clone for Router { +impl Clone for Router { fn clone(&self) -> Self { Self { path_router: self.path_router.clone(), @@ -72,9 +75,8 @@ impl Clone for Router { } } -impl Default for Router +impl Default for Router where - B: HttpBody + Send + 'static, S: Clone + Send + Sync + 'static, { fn default() -> Self { @@ -82,7 +84,7 @@ where } } -impl fmt::Debug for Router { +impl fmt::Debug for Router { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Router") .field("path_router", &self.path_router) @@ -96,9 +98,8 @@ pub(crate) const NEST_TAIL_PARAM: &str = "__private__axum_nest_tail_param"; pub(crate) const NEST_TAIL_PARAM_CAPTURE: &str = "/*__private__axum_nest_tail_param"; pub(crate) const FALLBACK_PARAM: &str = "__private__axum_fallback"; -impl Router +impl Router where - B: HttpBody + Send + 'static, S: Clone + Send + Sync + 'static, { /// Create a new `Router`. @@ -118,7 +119,7 @@ where #[doc = include_str!("../docs/routing/route.md")] #[track_caller] - pub fn route(mut self, path: &str, method_router: MethodRouter) -> Self { + pub fn route(mut self, path: &str, method_router: MethodRouter) -> Self { panic_on_err!(self.path_router.route(path, method_router)); self } @@ -126,11 +127,11 @@ where #[doc = include_str!("../docs/routing/route_service.md")] pub fn route_service(mut self, path: &str, service: T) -> Self where - T: Service, Error = Infallible> + Clone + Send + 'static, + T: Service + Clone + Send + 'static, T::Response: IntoResponse, T::Future: Send + 'static, { - let service = match try_downcast::, _>(service) { + let service = match try_downcast::, _>(service) { Ok(_) => { panic!( "Invalid route: `Router::route_service` cannot be used with `Router`s. \ @@ -146,7 +147,7 @@ where #[doc = include_str!("../docs/routing/nest.md")] #[track_caller] - pub fn nest(mut self, path: &str, router: Router) -> Self { + pub fn nest(mut self, path: &str, router: Router) -> Self { let Router { path_router, fallback_router, @@ -166,7 +167,7 @@ where #[track_caller] pub fn nest_service(mut self, path: &str, service: T) -> Self where - T: Service, Error = Infallible> + Clone + Send + 'static, + T: Service + Clone + Send + 'static, T::Response: IntoResponse, T::Future: Send + 'static, { @@ -178,7 +179,7 @@ where #[track_caller] pub fn merge(mut self, other: R) -> Self where - R: Into>, + R: Into>, { let Router { path_router, @@ -212,14 +213,13 @@ where } #[doc = include_str!("../docs/routing/layer.md")] - pub fn layer(self, layer: L) -> Router + pub fn layer(self, layer: L) -> Router where - L: Layer> + Clone + Send + 'static, - L::Service: Service> + Clone + Send + 'static, - >>::Response: IntoResponse + 'static, - >>::Error: Into + 'static, - >>::Future: Send + 'static, - NewReqBody: HttpBody + 'static, + L: Layer + Clone + Send + 'static, + L::Service: Service + Clone + Send + 'static, + >::Response: IntoResponse + 'static, + >::Error: Into + 'static, + >::Future: Send + 'static, { Router { path_router: self.path_router.layer(layer.clone()), @@ -232,11 +232,11 @@ where #[track_caller] pub fn route_layer(self, layer: L) -> Self where - L: Layer> + Clone + Send + 'static, - L::Service: Service> + Clone + Send + 'static, - >>::Response: IntoResponse + 'static, - >>::Error: Into + 'static, - >>::Future: Send + 'static, + L: Layer + Clone + Send + 'static, + L::Service: Service + Clone + Send + 'static, + >::Response: IntoResponse + 'static, + >::Error: Into + 'static, + >::Future: Send + 'static, { Router { path_router: self.path_router.route_layer(layer), @@ -249,7 +249,7 @@ where #[doc = include_str!("../docs/routing/fallback.md")] pub fn fallback(self, handler: H) -> Self where - H: Handler, + H: Handler, T: 'static, { let endpoint = Endpoint::MethodRouter(any(handler)); @@ -261,14 +261,14 @@ where /// See [`Router::fallback`] for more details. pub fn fallback_service(self, service: T) -> Self where - T: Service, Error = Infallible> + Clone + Send + 'static, + T: Service + Clone + Send + 'static, T::Response: IntoResponse, T::Future: Send + 'static, { self.fallback_endpoint(Endpoint::Route(Route::new(service))) } - fn fallback_endpoint(mut self, endpoint: Endpoint) -> Self { + fn fallback_endpoint(mut self, endpoint: Endpoint) -> Self { self.fallback_router.replace_endpoint("/", endpoint.clone()); self.fallback_router .replace_endpoint(&format!("/*{FALLBACK_PARAM}"), endpoint); @@ -277,7 +277,7 @@ where } #[doc = include_str!("../docs/routing/with_state.md")] - pub fn with_state(self, state: S) -> Router { + pub fn with_state(self, state: S) -> Router { Router { path_router: self.path_router.with_state(state.clone()), fallback_router: self.fallback_router.with_state(state), @@ -287,9 +287,9 @@ where pub(crate) fn call_with_state( &mut self, - mut req: Request, + mut req: Request, state: S, - ) -> RouteFuture { + ) -> RouteFuture { // required for opaque routers to still inherit the fallback // TODO(david): remove this feature in 0.7 if !self.default_fallback { @@ -303,7 +303,7 @@ where Err((mut req, state)) => { let super_fallback = req .extensions_mut() - .remove::>() + .remove::>() .map(|SuperFallback(path_router)| path_router.into_inner()); if let Some(mut super_fallback) = super_fallback { @@ -324,12 +324,81 @@ where } } } + + /// Convert the router into a borrowed [`Service`] with a fixed request body type, to aid type + /// inference. + /// + /// In some cases when calling methods from [`tower::ServiceExt`] on a [`Router`] you might get + /// type inference errors along the lines of + /// + /// ```not_rust + /// let response = router.ready().await?.call(request).await?; + /// ^^^^^ cannot infer type for type parameter `B` + /// ``` + /// + /// This happens because `Router` implements [`Service`] with `impl Service> for Router<()>`. + /// + /// For example: + /// + /// ```compile_fail + /// use axum::{ + /// Router, + /// routing::get, + /// http::Request, + /// body::Body, + /// }; + /// use tower::{Service, ServiceExt}; + /// + /// # async fn async_main() -> Result<(), Box> { + /// let mut router = Router::new().route("/", get(|| async {})); + /// let request = Request::new(Body::empty()); + /// let response = router.ready().await?.call(request).await?; + /// # Ok(()) + /// # } + /// ``` + /// + /// Calling `Router::as_service` fixes that: + /// + /// ``` + /// use axum::{ + /// Router, + /// routing::get, + /// http::Request, + /// body::Body, + /// }; + /// use tower::{Service, ServiceExt}; + /// + /// # async fn async_main() -> Result<(), Box> { + /// let mut router = Router::new().route("/", get(|| async {})); + /// let request = Request::new(Body::empty()); + /// let response = router.as_service().ready().await?.call(request).await?; + /// # Ok(()) + /// # } + /// ``` + /// + /// This is mainly used when calling `Router` in tests. It shouldn't be necessary when running + /// the `Router` normally via [`Router::into_make_service`]. + pub fn as_service(&mut self) -> RouterAsService<'_, B, S> { + RouterAsService { + router: self, + _marker: PhantomData, + } + } + + /// Convert the router into an owned [`Service`] with a fixed request body type, to aid type + /// inference. + /// + /// This is the same as [`Router::as_service`] instead it returns an owned [`Service`]. See + /// that method for more details. + pub fn into_service(self) -> RouterIntoService { + RouterIntoService { + router: self, + _marker: PhantomData, + } + } } -impl Router<(), B> -where - B: HttpBody + Send + 'static, -{ +impl Router { /// Convert this router into a [`MakeService`], that is a [`Service`] whose /// response is another service. /// @@ -345,10 +414,8 @@ where /// let app = Router::new().route("/", get(|| async { "Hi!" })); /// /// # async { - /// axum::Server::bind(&"0.0.0.0:3000".parse().unwrap()) - /// .serve(app.into_make_service()) - /// .await - /// .expect("server failed"); + /// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); + /// axum::serve(listener, app).await.unwrap(); /// # }; /// ``` /// @@ -368,13 +435,34 @@ where } } -impl Service> for Router<(), B> +// for `axum::serve(listener, router)` +#[cfg(feature = "tokio")] +const _: () = { + use crate::serve::IncomingStream; + + impl Service> for Router<()> { + type Response = Self; + type Error = Infallible; + type Future = std::future::Ready>; + + fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { + Poll::Ready(Ok(())) + } + + fn call(&mut self, _req: IncomingStream<'_>) -> Self::Future { + std::future::ready(Ok(self.clone())) + } + } +}; + +impl Service> for Router<()> where - B: HttpBody + Send + 'static, + B: HttpBody + Send + 'static, + B::Error: Into, { type Response = Response; type Error = Infallible; - type Future = RouteFuture; + type Future = RouteFuture; #[inline] fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll> { @@ -383,17 +471,96 @@ where #[inline] fn call(&mut self, req: Request) -> Self::Future { + let req = req.map(Body::new); self.call_with_state(req, ()) } } -enum Fallback { - Default(Route), - Service(Route), - BoxedHandler(BoxedIntoRoute), +/// A [`Router`] converted into a borrowed [`Service`] with a fixed body type. +/// +/// See [`Router::as_service`] for more details. +pub struct RouterAsService<'a, B, S = ()> { + router: &'a mut Router, + _marker: PhantomData, +} + +impl<'a, B> Service> for RouterAsService<'a, B, ()> +where + B: HttpBody + Send + 'static, + B::Error: Into, +{ + type Response = Response; + type Error = Infallible; + type Future = RouteFuture; + + #[inline] + fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + >>::poll_ready(self.router, cx) + } + + #[inline] + fn call(&mut self, req: Request) -> Self::Future { + self.router.call(req) + } +} + +impl<'a, B, S> fmt::Debug for RouterAsService<'a, B, S> +where + S: fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("RouterAsService") + .field("router", &self.router) + .finish() + } +} + +/// A [`Router`] converted into an owned [`Service`] with a fixed body type. +/// +/// See [`Router::into_service`] for more details. +pub struct RouterIntoService { + router: Router, + _marker: PhantomData, +} + +impl Service> for RouterIntoService +where + B: HttpBody + Send + 'static, + B::Error: Into, +{ + type Response = Response; + type Error = Infallible; + type Future = RouteFuture; + + #[inline] + fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + >>::poll_ready(&mut self.router, cx) + } + + #[inline] + fn call(&mut self, req: Request) -> Self::Future { + self.router.call(req) + } +} + +impl fmt::Debug for RouterIntoService +where + S: fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("RouterIntoService") + .field("router", &self.router) + .finish() + } +} + +enum Fallback { + Default(Route), + Service(Route), + BoxedHandler(BoxedIntoRoute), } -impl Fallback +impl Fallback where S: Clone, { @@ -405,13 +572,11 @@ where } } - fn map(self, f: F) -> Fallback + fn map(self, f: F) -> Fallback where S: 'static, - B: 'static, E: 'static, - F: FnOnce(Route) -> Route + Clone + Send + 'static, - B2: HttpBody + 'static, + F: FnOnce(Route) -> Route + Clone + Send + 'static, E2: 'static, { match self { @@ -421,7 +586,7 @@ where } } - fn with_state(self, state: S) -> Fallback { + fn with_state(self, state: S) -> Fallback { match self { Fallback::Default(route) => Fallback::Default(route), Fallback::Service(route) => Fallback::Service(route), @@ -430,7 +595,7 @@ where } } -impl Clone for Fallback { +impl Clone for Fallback { fn clone(&self) -> Self { match self { Self::Default(inner) => Self::Default(inner.clone()), @@ -440,7 +605,7 @@ impl Clone for Fallback { } } -impl fmt::Debug for Fallback { +impl fmt::Debug for Fallback { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::Default(inner) => f.debug_tuple("Default").field(inner).finish(), @@ -451,24 +616,22 @@ impl fmt::Debug for Fallback { } #[allow(clippy::large_enum_variant)] -enum Endpoint { - MethodRouter(MethodRouter), - Route(Route), +enum Endpoint { + MethodRouter(MethodRouter), + Route(Route), } -impl Endpoint +impl Endpoint where - B: HttpBody + Send + 'static, S: Clone + Send + Sync + 'static, { - fn layer(self, layer: L) -> Endpoint + fn layer(self, layer: L) -> Endpoint where - L: Layer> + Clone + Send + 'static, - L::Service: Service> + Clone + Send + 'static, - >>::Response: IntoResponse + 'static, - >>::Error: Into + 'static, - >>::Future: Send + 'static, - NewReqBody: HttpBody + 'static, + L: Layer + Clone + Send + 'static, + L::Service: Service + Clone + Send + 'static, + >::Response: IntoResponse + 'static, + >::Error: Into + 'static, + >::Future: Send + 'static, { match self { Endpoint::MethodRouter(method_router) => { @@ -479,7 +642,7 @@ where } } -impl Clone for Endpoint { +impl Clone for Endpoint { fn clone(&self) -> Self { match self { Self::MethodRouter(inner) => Self::MethodRouter(inner.clone()), @@ -488,7 +651,7 @@ impl Clone for Endpoint { } } -impl fmt::Debug for Endpoint { +impl fmt::Debug for Endpoint { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::MethodRouter(method_router) => { @@ -499,11 +662,11 @@ impl fmt::Debug for Endpoint { } } -struct SuperFallback(SyncWrapper>); +struct SuperFallback(SyncWrapper>); #[test] #[allow(warnings)] fn traits() { use crate::test_helpers::*; - assert_send::>(); + assert_send::>(); } diff --git a/axum/src/routing/path_router.rs b/axum/src/routing/path_router.rs index ca618e7548..6baa79431f 100644 --- a/axum/src/routing/path_router.rs +++ b/axum/src/routing/path_router.rs @@ -1,6 +1,5 @@ -use crate::body::HttpBody; +use crate::extract::Request; use axum_core::response::IntoResponse; -use http::Request; use matchit::MatchError; use std::{borrow::Cow, collections::HashMap, convert::Infallible, fmt, sync::Arc}; use tower_layer::Layer; @@ -11,21 +10,20 @@ use super::{ RouteId, NEST_TAIL_PARAM, }; -pub(super) struct PathRouter { - routes: HashMap>, +pub(super) struct PathRouter { + routes: HashMap>, node: Arc, prev_route_id: RouteId, } -impl PathRouter +impl PathRouter where - B: HttpBody + Send + 'static, S: Clone + Send + Sync + 'static, { pub(super) fn route( &mut self, path: &str, - method_router: MethodRouter, + method_router: MethodRouter, ) -> Result<(), Cow<'static, str>> { fn validate_path(path: &str) -> Result<(), &'static str> { if path.is_empty() { @@ -72,7 +70,7 @@ where service: T, ) -> Result<(), Cow<'static, str>> where - T: Service, Error = Infallible> + Clone + Send + 'static, + T: Service + Clone + Send + 'static, T::Response: IntoResponse, T::Future: Send + 'static, { @@ -82,7 +80,7 @@ where pub(super) fn route_endpoint( &mut self, path: &str, - endpoint: Endpoint, + endpoint: Endpoint, ) -> Result<(), Cow<'static, str>> { if path.is_empty() { return Err("Paths must start with a `/`. Use \"/\" for root routes".into()); @@ -109,7 +107,7 @@ where pub(super) fn merge( &mut self, - other: PathRouter, + other: PathRouter, ) -> Result<(), Cow<'static, str>> { let PathRouter { routes, @@ -134,7 +132,7 @@ where pub(super) fn nest( &mut self, path: &str, - router: PathRouter, + router: PathRouter, ) -> Result<(), Cow<'static, str>> { let prefix = validate_nest_path(path); @@ -167,7 +165,7 @@ where pub(super) fn nest_service(&mut self, path: &str, svc: T) -> Result<(), Cow<'static, str>> where - T: Service, Error = Infallible> + Clone + Send + 'static, + T: Service + Clone + Send + 'static, T::Response: IntoResponse, T::Future: Send + 'static, { @@ -196,14 +194,13 @@ where Ok(()) } - pub(super) fn layer(self, layer: L) -> PathRouter + pub(super) fn layer(self, layer: L) -> PathRouter where - L: Layer> + Clone + Send + 'static, - L::Service: Service> + Clone + Send + 'static, - >>::Response: IntoResponse + 'static, - >>::Error: Into + 'static, - >>::Future: Send + 'static, - NewReqBody: HttpBody + 'static, + L: Layer + Clone + Send + 'static, + L::Service: Service + Clone + Send + 'static, + >::Response: IntoResponse + 'static, + >::Error: Into + 'static, + >::Future: Send + 'static, { let routes = self .routes @@ -224,11 +221,11 @@ where #[track_caller] pub(super) fn route_layer(self, layer: L) -> Self where - L: Layer> + Clone + Send + 'static, - L::Service: Service> + Clone + Send + 'static, - >>::Response: IntoResponse + 'static, - >>::Error: Into + 'static, - >>::Future: Send + 'static, + L: Layer + Clone + Send + 'static, + L::Service: Service + Clone + Send + 'static, + >::Response: IntoResponse + 'static, + >::Error: Into + 'static, + >::Future: Send + 'static, { if self.routes.is_empty() { panic!( @@ -253,12 +250,12 @@ where } } - pub(super) fn with_state(self, state: S) -> PathRouter { + pub(super) fn with_state(self, state: S) -> PathRouter { let routes = self .routes .into_iter() .map(|(id, endpoint)| { - let endpoint: Endpoint = match endpoint { + let endpoint: Endpoint = match endpoint { Endpoint::MethodRouter(method_router) => { Endpoint::MethodRouter(method_router.with_state(state.clone())) } @@ -277,9 +274,9 @@ where pub(super) fn call_with_state( &mut self, - mut req: Request, + mut req: Request, state: S, - ) -> Result, (Request, S)> { + ) -> Result, (Request, S)> { #[cfg(feature = "original-uri")] { use crate::extract::OriginalUri; @@ -329,7 +326,7 @@ where } } - pub(super) fn replace_endpoint(&mut self, path: &str, endpoint: Endpoint) { + pub(super) fn replace_endpoint(&mut self, path: &str, endpoint: Endpoint) { match self.node.at(path) { Ok(match_) => { let id = *match_.value; @@ -352,7 +349,7 @@ where } } -impl Default for PathRouter { +impl Default for PathRouter { fn default() -> Self { Self { routes: Default::default(), @@ -362,7 +359,7 @@ impl Default for PathRouter { } } -impl fmt::Debug for PathRouter { +impl fmt::Debug for PathRouter { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("PathRouter") .field("routes", &self.routes) @@ -371,7 +368,7 @@ impl fmt::Debug for PathRouter } } -impl Clone for PathRouter { +impl Clone for PathRouter { fn clone(&self) -> Self { Self { routes: self.routes.clone(), diff --git a/axum/src/routing/route.rs b/axum/src/routing/route.rs index 1667db1607..0a2713a8d2 100644 --- a/axum/src/routing/route.rs +++ b/axum/src/routing/route.rs @@ -1,12 +1,12 @@ use crate::{ - body::{boxed, Body, Empty, HttpBody}, + body::{Body, HttpBody}, response::Response, }; -use axum_core::response::IntoResponse; +use axum_core::{extract::Request, response::IntoResponse}; use bytes::Bytes; use http::{ header::{self, CONTENT_LENGTH}, - HeaderMap, HeaderValue, Request, + HeaderMap, HeaderValue, }; use pin_project_lite::pin_project; use std::{ @@ -27,12 +27,12 @@ use tower_service::Service; /// /// You normally shouldn't need to care about this type. It's used in /// [`Router::layer`](super::Router::layer). -pub struct Route(BoxCloneService, Response, E>); +pub struct Route(BoxCloneService); -impl Route { +impl Route { pub(crate) fn new(svc: T) -> Self where - T: Service, Error = E> + Clone + Send + 'static, + T: Service + Clone + Send + 'static, T::Response: IntoResponse + 'static, T::Future: Send + 'static, { @@ -43,22 +43,22 @@ impl Route { pub(crate) fn oneshot_inner( &mut self, - req: Request, - ) -> Oneshot, Response, E>, Request> { + req: Request, + ) -> Oneshot, Request> { self.0.clone().oneshot(req) } - pub(crate) fn layer(self, layer: L) -> Route + pub(crate) fn layer(self, layer: L) -> Route where - L: Layer> + Clone + Send + 'static, - L::Service: Service> + Clone + Send + 'static, - >>::Response: IntoResponse + 'static, - >>::Error: Into + 'static, - >>::Future: Send + 'static, - NewReqBody: 'static, + L: Layer> + Clone + Send + 'static, + L::Service: Service + Clone + Send + 'static, + >::Response: IntoResponse + 'static, + >::Error: Into + 'static, + >::Future: Send + 'static, NewError: 'static, { let layer = ServiceBuilder::new() + .map_request(|req: Request<_>| req.map(Body::new)) .map_err(Into::into) .layer(MapResponseLayer::new(IntoResponse::into_response)) .layer(layer) @@ -68,25 +68,26 @@ impl Route { } } -impl Clone for Route { +impl Clone for Route { fn clone(&self) -> Self { Self(self.0.clone()) } } -impl fmt::Debug for Route { +impl fmt::Debug for Route { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Route").finish() } } -impl Service> for Route +impl Service> for Route where - B: HttpBody, + B: HttpBody + Send + 'static, + B::Error: Into, { type Response = Response; type Error = E; - type Future = RouteFuture; + type Future = RouteFuture; #[inline] fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll> { @@ -95,15 +96,16 @@ where #[inline] fn call(&mut self, req: Request) -> Self::Future { + let req = req.map(Body::new); RouteFuture::from_future(self.oneshot_inner(req)) } } pin_project! { /// Response future for [`Route`]. - pub struct RouteFuture { + pub struct RouteFuture { #[pin] - kind: RouteFutureKind, + kind: RouteFutureKind, strip_body: bool, allow_header: Option, } @@ -111,12 +113,12 @@ pin_project! { pin_project! { #[project = RouteFutureKindProj] - enum RouteFutureKind { + enum RouteFutureKind { Future { #[pin] future: Oneshot< - BoxCloneService, Response, E>, - Request, + BoxCloneService, + Request, >, }, Response { @@ -125,9 +127,9 @@ pin_project! { } } -impl RouteFuture { +impl RouteFuture { pub(crate) fn from_future( - future: Oneshot, Response, E>, Request>, + future: Oneshot, Request>, ) -> Self { Self { kind: RouteFutureKind::Future { future }, @@ -147,10 +149,7 @@ impl RouteFuture { } } -impl Future for RouteFuture -where - B: HttpBody, -{ +impl Future for RouteFuture { type Output = Result; #[inline] @@ -174,7 +173,7 @@ where set_content_length(res.size_hint(), res.headers_mut()); let res = if *this.strip_body { - res.map(|_| boxed(Empty::new())) + res.map(|_| Body::empty()) } else { res }; @@ -217,22 +216,19 @@ fn set_content_length(size_hint: http_body::SizeHint, headers: &mut HeaderMap) { pin_project! { /// A [`RouteFuture`] that always yields a [`Response`]. - pub struct InfallibleRouteFuture { + pub struct InfallibleRouteFuture { #[pin] - future: RouteFuture, + future: RouteFuture, } } -impl InfallibleRouteFuture { - pub(crate) fn new(future: RouteFuture) -> Self { +impl InfallibleRouteFuture { + pub(crate) fn new(future: RouteFuture) -> Self { Self { future } } } -impl Future for InfallibleRouteFuture -where - B: HttpBody, -{ +impl Future for InfallibleRouteFuture { type Output = Response; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { diff --git a/axum/src/routing/tests/fallback.rs b/axum/src/routing/tests/fallback.rs index 9aa9fbe6aa..6833dad398 100644 --- a/axum/src/routing/tests/fallback.rs +++ b/axum/src/routing/tests/fallback.rs @@ -176,7 +176,7 @@ async fn fallback_inherited_into_nested_router_service() { .with_state("inner"); // with a different state - let app = Router::<()>::new() + let app = Router::new() .nest_service("/foo", inner) .fallback(outer_fallback); @@ -198,7 +198,7 @@ async fn fallback_inherited_into_nested_opaque_service() { .boxed_clone(); // with a different state - let app = Router::<()>::new() + let app = Router::new() .nest_service("/foo", inner) .fallback(outer_fallback); diff --git a/axum/src/routing/tests/get_to_head.rs b/axum/src/routing/tests/get_to_head.rs index b46114c60e..cedf84918e 100644 --- a/axum/src/routing/tests/get_to_head.rs +++ b/axum/src/routing/tests/get_to_head.rs @@ -45,7 +45,7 @@ mod for_services { async fn get_handles_head() { let app = Router::new().route( "/", - get_service(service_fn(|_req: Request| async move { + get_service(service_fn(|_req: Request| async move { Ok::<_, Infallible>( ([("x-some-header", "foobar")], "you shouldn't see this").into_response(), ) diff --git a/axum/src/routing/tests/merge.rs b/axum/src/routing/tests/merge.rs index 0344a87939..31b42d8336 100644 --- a/axum/src/routing/tests/merge.rs +++ b/axum/src/routing/tests/merge.rs @@ -195,13 +195,13 @@ async fn services() { let app = Router::new() .route( "/foo", - get_service(service_fn(|_: Request| async { + get_service(service_fn(|_: Request| async { Ok::<_, Infallible>(Response::new(Body::empty())) })), ) .merge(Router::new().route( "/bar", - get_service(service_fn(|_: Request| async { + get_service(service_fn(|_: Request| async { Ok::<_, Infallible>(Response::new(Body::empty())) })), )); @@ -218,7 +218,7 @@ async fn services() { async fn all_the_uris( uri: Uri, OriginalUri(original_uri): OriginalUri, - req: Request, + req: Request, ) -> impl IntoResponse { Json(json!({ "uri": uri.to_string(), diff --git a/axum/src/routing/tests/mod.rs b/axum/src/routing/tests/mod.rs index 950d601a4b..40585eed8f 100644 --- a/axum/src/routing/tests/mod.rs +++ b/axum/src/routing/tests/mod.rs @@ -1,9 +1,9 @@ use crate::{ - body::{Bytes, Empty}, + body::{Body, Bytes}, error_handling::HandleErrorLayer, extract::{self, DefaultBodyLimit, FromRef, Path, State}, handler::{Handler, HandlerWithoutStateExt}, - response::IntoResponse, + response::{IntoResponse, Response}, routing::{ delete, get, get_service, on, on_service, patch, patch_service, path_router::path_for_nested_route, post, MethodFilter, @@ -14,9 +14,9 @@ use crate::{ }, BoxError, Extension, Json, Router, }; +use axum_core::extract::Request; use futures_util::stream::StreamExt; -use http::{header::ALLOW, header::CONTENT_LENGTH, HeaderMap, Request, Response, StatusCode, Uri}; -use hyper::Body; +use http::{header::ALLOW, header::CONTENT_LENGTH, HeaderMap, StatusCode, Uri}; use serde::Deserialize; use serde_json::json; use std::{ @@ -38,15 +38,15 @@ mod nest; #[crate::test] async fn hello_world() { - async fn root(_: Request) -> &'static str { + async fn root(_: Request) -> &'static str { "Hello, World!" } - async fn foo(_: Request) -> &'static str { + async fn foo(_: Request) -> &'static str { "foo" } - async fn users_create(_: Request) -> &'static str { + async fn users_create(_: Request) -> &'static str { "users#create" } @@ -74,13 +74,12 @@ async fn routing() { let app = Router::new() .route( "/users", - get(|_: Request| async { "users#index" }) - .post(|_: Request| async { "users#create" }), + get(|_: Request| async { "users#index" }).post(|_: Request| async { "users#create" }), ) - .route("/users/:id", get(|_: Request| async { "users#show" })) + .route("/users/:id", get(|_: Request| async { "users#show" })) .route( "/users/:id/action", - get(|_: Request| async { "users#action" }), + get(|_: Request| async { "users#action" }), ); let client = TestClient::new(app); @@ -110,12 +109,8 @@ async fn router_type_doesnt_change() { let app: Router = Router::new() .route( "/", - on(MethodFilter::GET, |_: Request| async { - "hi from GET" - }) - .on(MethodFilter::POST, |_: Request| async { - "hi from POST" - }), + on(MethodFilter::GET, |_: Request| async { "hi from GET" }) + .on(MethodFilter::POST, |_: Request| async { "hi from POST" }), ) .layer(tower_http::compression::CompressionLayer::new()); @@ -135,22 +130,22 @@ async fn routing_between_services() { use std::convert::Infallible; use tower::service_fn; - async fn handle(_: Request) -> &'static str { + async fn handle(_: Request) -> &'static str { "handler" } let app = Router::new() .route( "/one", - get_service(service_fn(|_: Request| async { + get_service(service_fn(|_: Request| async { Ok::<_, Infallible>(Response::new(Body::from("one get"))) })) - .post_service(service_fn(|_: Request| async { + .post_service(service_fn(|_: Request| async { Ok::<_, Infallible>(Response::new(Body::from("one post"))) })) .on_service( MethodFilter::PUT, - service_fn(|_: Request| async { + service_fn(|_: Request| async { Ok::<_, Infallible>(Response::new(Body::from("one put"))) }), ), @@ -181,7 +176,7 @@ async fn middleware_on_single_route() { use tower::ServiceBuilder; use tower_http::{compression::CompressionLayer, trace::TraceLayer}; - async fn handle(_: Request) -> &'static str { + async fn handle(_: Request) -> &'static str { "Hello, World!" } @@ -205,8 +200,8 @@ async fn middleware_on_single_route() { #[crate::test] async fn service_in_bottom() { - async fn handler(_req: Request) -> Result, Infallible> { - Ok(Response::new(hyper::Body::empty())) + async fn handler(_req: Request) -> Result, Infallible> { + Ok(Response::new(Body::empty())) } let app = Router::new().route("/", get_service(service_fn(handler))); @@ -243,7 +238,7 @@ async fn wrong_method_service() { struct Svc; impl Service for Svc { - type Response = Response>; + type Response = Response; type Error = Infallible; type Future = Ready>; @@ -252,7 +247,7 @@ async fn wrong_method_service() { } fn call(&mut self, _req: R) -> Self::Future { - ready(Ok(Response::new(Empty::new()))) + ready(Ok(().into_response())) } } @@ -279,7 +274,7 @@ async fn wrong_method_service() { #[crate::test] async fn multiple_methods_for_one_handler() { - async fn root(_: Request) -> &'static str { + async fn root(_: Request) -> &'static str { "Hello, World!" } @@ -659,7 +654,7 @@ async fn body_limited_by_default() { println!("calling {uri}"); let stream = futures_util::stream::repeat("a".repeat(1000)).map(Ok::<_, hyper::Error>); - let body = Body::wrap_stream(stream); + let body = reqwest::Body::wrap_stream(stream); let res_future = client .post(uri) @@ -683,7 +678,7 @@ async fn disabling_the_default_limit() { let client = TestClient::new(app); // `DEFAULT_LIMIT` is 2mb so make a body larger than that - let body = Body::from("a".repeat(3_000_000)); + let body = reqwest::Body::from("a".repeat(3_000_000)); let res = client.post("/").body(body).send().await; @@ -724,14 +719,14 @@ async fn changing_the_default_limit() { let res = client .post("/") - .body(Body::from("a".repeat(new_limit))) + .body(reqwest::Body::from("a".repeat(new_limit))) .send() .await; assert_eq!(res.status(), StatusCode::OK); let res = client .post("/") - .body(Body::from("a".repeat(new_limit + 1))) + .body(reqwest::Body::from("a".repeat(new_limit + 1))) .send() .await; assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE); @@ -755,7 +750,7 @@ async fn limited_body_with_streaming_body() { let stream = futures_util::stream::iter(vec![Ok::<_, hyper::Error>("a".repeat(LIMIT))]); let res = client .post("/") - .body(Body::wrap_stream(stream)) + .body(reqwest::Body::wrap_stream(stream)) .send() .await; assert_eq!(res.status(), StatusCode::OK); @@ -763,7 +758,7 @@ async fn limited_body_with_streaming_body() { let stream = futures_util::stream::iter(vec![Ok::<_, hyper::Error>("a".repeat(LIMIT * 2))]); let res = client .post("/") - .body(Body::wrap_stream(stream)) + .body(reqwest::Body::wrap_stream(stream)) .send() .await; assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE); diff --git a/axum/src/routing/tests/nest.rs b/axum/src/routing/tests/nest.rs index 0544f8be59..a9119eb3cf 100644 --- a/axum/src/routing/tests/nest.rs +++ b/axum/src/routing/tests/nest.rs @@ -1,5 +1,5 @@ use super::*; -use crate::{body::boxed, extract::Extension}; +use crate::extract::Extension; use std::collections::HashMap; use tower_http::services::ServeDir; @@ -141,7 +141,7 @@ async fn nested_url_extractor() { .route("/baz", get(|uri: Uri| async move { uri.to_string() })) .route( "/qux", - get(|req: Request| async move { req.uri().to_string() }), + get(|req: Request| async move { req.uri().to_string() }), ), ), ); @@ -185,8 +185,8 @@ async fn nested_service_sees_stripped_uri() { "/bar", Router::new().route_service( "/baz", - service_fn(|req: Request| async move { - let body = boxed(Body::from(req.uri().to_string())); + service_fn(|req: Request| async move { + let body = Body::from(req.uri().to_string()); Ok::<_, Infallible>(Response::new(body)) }), ), @@ -264,7 +264,7 @@ async fn multiple_top_level_nests() { #[crate::test] #[should_panic(expected = "Invalid route: nested routes cannot contain wildcards (*)")] async fn nest_cannot_contain_wildcards() { - _ = Router::<(), Body>::new().nest("/one/*rest", Router::new()); + _ = Router::<()>::new().nest("/one/*rest", Router::new()); } #[crate::test] diff --git a/axum/src/serve.rs b/axum/src/serve.rs new file mode 100644 index 0000000000..83f529c8c3 --- /dev/null +++ b/axum/src/serve.rs @@ -0,0 +1,234 @@ +//! Serve services. + +use std::{convert::Infallible, io, net::SocketAddr}; + +use axum_core::{body::Body, extract::Request, response::Response}; +use futures_util::{future::poll_fn, FutureExt}; +use hyper1::server::conn::http1; +use tokio::net::{TcpListener, TcpStream}; +use tower_hyper_http_body_compat::{HttpBody04ToHttpBody1, HttpBody1ToHttpBody04}; +use tower_service::Service; + +/// Serve the service with the supplied listener. +/// +/// This method of running a service is intentionally simple and doesn't support any configuration. +/// Use hyper or hyper-util if you need configuration. +/// +/// It only supports HTTP/1. +/// +/// # Examples +/// +/// Serving a [`Router`]: +/// +/// ``` +/// use axum::{Router, routing::get}; +/// +/// # async { +/// let router = Router::new().route("/", get(|| async { "Hello, World!" })); +/// +/// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); +/// axum::serve(listener, router).await.unwrap(); +/// # }; +/// ``` +/// +/// See also [`Router::into_make_service_with_connect_info`]. +/// +/// Serving a [`MethodRouter`]: +/// +/// ``` +/// use axum::routing::get; +/// +/// # async { +/// let router = get(|| async { "Hello, World!" }); +/// +/// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); +/// axum::serve(listener, router).await.unwrap(); +/// # }; +/// ``` +/// +/// See also [`MethodRouter::into_make_service_with_connect_info`]. +/// +/// Serving a [`Handler`]: +/// +/// ``` +/// use axum::handler::HandlerWithoutStateExt; +/// +/// # async { +/// async fn handler() -> &'static str { +/// "Hello, World!" +/// } +/// +/// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); +/// axum::serve(listener, handler.into_make_service()).await.unwrap(); +/// # }; +/// ``` +/// +/// See also [`HandlerWithoutStateExt::into_make_service_with_connect_info`] and +/// [`HandlerService::into_make_service_with_connect_info`]. +/// +/// [`Router`]: crate::Router +/// [`Router::into_make_service_with_connect_info`]: crate::Router::into_make_service_with_connect_info +/// [`MethodRouter`]: crate::routing::MethodRouter +/// [`MethodRouter::into_make_service_with_connect_info`]: crate::routing::MethodRouter::into_make_service_with_connect_info +/// [`Handler`]: crate::handler::Handler +/// [`HandlerWithoutStateExt::into_make_service_with_connect_info`]: crate::handler::HandlerWithoutStateExt::into_make_service_with_connect_info +/// [`HandlerService::into_make_service_with_connect_info`]: crate::handler::HandlerService::into_make_service_with_connect_info +#[cfg(feature = "tokio")] +pub async fn serve(tcp_listener: TcpListener, mut make_service: M) -> io::Result<()> +where + M: for<'a> Service, Error = Infallible, Response = S>, + S: Service + Clone + Send + 'static, + S::Future: Send, +{ + loop { + let (tcp_stream, remote_addr) = tcp_listener.accept().await?; + + poll_fn(|cx| make_service.poll_ready(cx)) + .await + .unwrap_or_else(|err| match err {}); + + let mut service = make_service + .call(IncomingStream { + tcp_stream: &tcp_stream, + remote_addr, + }) + .await + .unwrap_or_else(|err| match err {}); + + let service = hyper1::service::service_fn(move |req: Request| { + let req = req.map(|body| { + // wont need this when axum uses http-body 1.0 + let http_body_04 = HttpBody1ToHttpBody04::new(body); + Body::new(http_body_04) + }); + + // doing this saves cloning the service just to await the service being ready + // + // services like `Router` are always ready, so assume the service + // we're running here is also always ready... + match futures_util::future::poll_fn(|cx| service.poll_ready(cx)).now_or_never() { + Some(Ok(())) => {} + Some(Err(err)) => match err {}, + None => { + // ...otherwise load shed + let mut res = Response::new(HttpBody04ToHttpBody1::new(Body::empty())); + *res.status_mut() = http::StatusCode::SERVICE_UNAVAILABLE; + return std::future::ready(Ok(res)).left_future(); + } + } + + let future = service.call(req); + + async move { + let response = future + .await + .unwrap_or_else(|err| match err {}) + // wont need this when axum uses http-body 1.0 + .map(HttpBody04ToHttpBody1::new); + + Ok::<_, Infallible>(response) + } + .right_future() + }); + + tokio::task::spawn(async move { + match http1::Builder::new() + .serve_connection(tcp_stream, service) + // for websockets + .with_upgrades() + .await + { + Ok(()) => {} + Err(_err) => { + // This error only appears when the client doesn't send a request and + // terminate the connection. + // + // If client sends one request then terminate connection whenever, it doesn't + // appear. + } + } + }); + } +} + +/// An incoming stream. +/// +/// Used with [`serve`] and [`IntoMakeServiceWithConnectInfo`]. +/// +/// [`IntoMakeServiceWithConnectInfo`]: crate::extract::connect_info::IntoMakeServiceWithConnectInfo +#[derive(Debug)] +pub struct IncomingStream<'a> { + tcp_stream: &'a TcpStream, + remote_addr: SocketAddr, +} + +impl IncomingStream<'_> { + /// Returns the local address that this stream is bound to. + pub fn local_addr(&self) -> std::io::Result { + self.tcp_stream.local_addr() + } + + /// Returns the remote address that this stream is bound to. + pub fn remote_addr(&self) -> SocketAddr { + self.remote_addr + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + handler::{Handler, HandlerWithoutStateExt}, + routing::get, + Router, + }; + + #[allow(dead_code, unused_must_use)] + async fn if_it_compiles_it_works() { + let router: Router = Router::new(); + + let addr = "0.0.0.0:0"; + + // router + serve(TcpListener::bind(addr).await.unwrap(), router.clone()); + serve( + TcpListener::bind(addr).await.unwrap(), + router.clone().into_make_service(), + ); + serve( + TcpListener::bind(addr).await.unwrap(), + router.into_make_service_with_connect_info::(), + ); + + // method router + serve(TcpListener::bind(addr).await.unwrap(), get(handler)); + serve( + TcpListener::bind(addr).await.unwrap(), + get(handler).into_make_service(), + ); + serve( + TcpListener::bind(addr).await.unwrap(), + get(handler).into_make_service_with_connect_info::(), + ); + + // handler + serve( + TcpListener::bind(addr).await.unwrap(), + handler.into_service(), + ); + serve( + TcpListener::bind(addr).await.unwrap(), + handler.with_state(()), + ); + serve( + TcpListener::bind(addr).await.unwrap(), + handler.into_make_service(), + ); + serve( + TcpListener::bind(addr).await.unwrap(), + handler.into_make_service_with_connect_info::(), + ); + } + + async fn handler() {} +} diff --git a/axum/src/test_helpers/mod.rs b/axum/src/test_helpers/mod.rs index de4554905e..3bb1535e40 100644 --- a/axum/src/test_helpers/mod.rs +++ b/axum/src/test_helpers/mod.rs @@ -1,6 +1,6 @@ #![allow(clippy::disallowed_names)] -use crate::{body::HttpBody, BoxError}; +use crate::{extract::Request, response::Response, serve}; mod test_client; pub(crate) use self::test_client::*; @@ -9,6 +9,5 @@ pub(crate) mod tracing_helpers; pub(crate) fn assert_send() {} pub(crate) fn assert_sync() {} -pub(crate) fn assert_unpin() {} pub(crate) struct NotSendSync(*const ()); diff --git a/axum/src/test_helpers/test_client.rs b/axum/src/test_helpers/test_client.rs index d1d73f6c1d..9e1858cb97 100644 --- a/axum/src/test_helpers/test_client.rs +++ b/axum/src/test_helpers/test_client.rs @@ -1,11 +1,11 @@ -use super::{BoxError, HttpBody}; +use super::{serve, Request, Response}; use bytes::Bytes; use http::{ header::{HeaderName, HeaderValue}, - Request, StatusCode, + StatusCode, }; -use hyper::{Body, Server}; -use std::net::{SocketAddr, TcpListener}; +use std::{convert::Infallible, net::SocketAddr}; +use tokio::net::TcpListener; use tower::make::Shared; use tower_service::Service; @@ -15,22 +15,22 @@ pub(crate) struct TestClient { } impl TestClient { - pub(crate) fn new(svc: S) -> Self + pub(crate) fn new(svc: S) -> Self where - S: Service, Response = http::Response> + Clone + Send + 'static, - ResBody: HttpBody + Send + 'static, - ResBody::Data: Send, - ResBody::Error: Into, + S: Service + Clone + Send + 'static, S::Future: Send, - S::Error: Into, { - let listener = TcpListener::bind("127.0.0.1:0").expect("Could not bind ephemeral socket"); + let std_listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + std_listener.set_nonblocking(true).unwrap(); + let listener = TcpListener::from_std(std_listener).unwrap(); + let addr = listener.local_addr().unwrap(); println!("Listening on {addr}"); tokio::spawn(async move { - let server = Server::from_tcp(listener).unwrap().serve(Shared::new(svc)); - server.await.expect("server error"); + serve(listener, Shared::new(svc)) + .await + .expect("server error") }); let client = reqwest::Client::builder() diff --git a/deny.toml b/deny.toml index c543455c59..23347652ae 100644 --- a/deny.toml +++ b/deny.toml @@ -25,6 +25,10 @@ skip-tree = [ { name = "spin" }, # lots still pulls in syn 1.x { name = "syn" }, + # until 1.0 is out we're pulling in both 0.14 and 1.0-rc.x + { name = "hyper" }, + # pulled in by tracing-subscriber + { name = "regex-syntax" } ] [sources] diff --git a/examples/anyhow-error-response/src/main.rs b/examples/anyhow-error-response/src/main.rs index 6854831340..b7a2416a4a 100644 --- a/examples/anyhow-error-response/src/main.rs +++ b/examples/anyhow-error-response/src/main.rs @@ -10,18 +10,16 @@ use axum::{ routing::get, Router, }; -use std::net::SocketAddr; #[tokio::main] async fn main() { let app = Router::new().route("/", get(handler)); - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - println!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + println!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } async fn handler() -> Result<(), AppError> { diff --git a/examples/chat/src/main.rs b/examples/chat/src/main.rs index 3b49c3e81a..f7298c3436 100644 --- a/examples/chat/src/main.rs +++ b/examples/chat/src/main.rs @@ -18,7 +18,6 @@ use axum::{ use futures::{sink::SinkExt, stream::StreamExt}; use std::{ collections::HashSet, - net::SocketAddr, sync::{Arc, Mutex}, }; use tokio::sync::broadcast; @@ -53,12 +52,11 @@ async fn main() { .route("/websocket", get(websocket_handler)) .with_state(app_state); - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } async fn websocket_handler( diff --git a/examples/consume-body-in-extractor-or-middleware/src/main.rs b/examples/consume-body-in-extractor-or-middleware/src/main.rs index 548e4f0e5a..fd63fcb1ff 100644 --- a/examples/consume-body-in-extractor-or-middleware/src/main.rs +++ b/examples/consume-body-in-extractor-or-middleware/src/main.rs @@ -6,17 +6,15 @@ use axum::{ async_trait, - body::{self, BoxBody, Bytes, Full}, - extract::FromRequest, - http::{Request, StatusCode}, + body::{Body, Bytes}, + extract::{FromRequest, Request}, + http::StatusCode, middleware::{self, Next}, response::{IntoResponse, Response}, routing::post, Router, }; -use std::net::SocketAddr; use tower::ServiceBuilder; -use tower_http::ServiceBuilderExt; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] @@ -29,25 +27,19 @@ async fn main() { .with(tracing_subscriber::fmt::layer()) .init(); - let app = Router::new().route("/", post(handler)).layer( - ServiceBuilder::new() - .map_request_body(body::boxed) - .layer(middleware::from_fn(print_request_body)), - ); + let app = Router::new() + .route("/", post(handler)) + .layer(ServiceBuilder::new().layer(middleware::from_fn(print_request_body))); - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } // middleware that shows how to consume the request body upfront -async fn print_request_body( - request: Request, - next: Next, -) -> Result { +async fn print_request_body(request: Request, next: Next) -> Result { let request = buffer_request_body(request).await?; Ok(next.run(request).await) @@ -55,7 +47,7 @@ async fn print_request_body( // the trick is to take the request apart, buffer the body, do what you need to do, then put // the request back together -async fn buffer_request_body(request: Request) -> Result, Response> { +async fn buffer_request_body(request: Request) -> Result { let (parts, body) = request.into_parts(); // this wont work if the body is an long running stream @@ -65,7 +57,7 @@ async fn buffer_request_body(request: Request) -> Result FromRequest for BufferRequestBody +impl FromRequest for BufferRequestBody where S: Send + Sync, { type Rejection = Response; - async fn from_request(req: Request, state: &S) -> Result { + async fn from_request(req: Request, state: &S) -> Result { let body = Bytes::from_request(req, state) .await .map_err(|err| err.into_response())?; diff --git a/examples/cors/src/main.rs b/examples/cors/src/main.rs index a0a5e8d8db..bbd192065b 100644 --- a/examples/cors/src/main.rs +++ b/examples/cors/src/main.rs @@ -40,10 +40,8 @@ async fn main() { async fn serve(app: Router, port: u16) { let addr = SocketAddr::from(([127, 0, 0, 1], port)); - axum::Server::bind(&addr) - .serve(app.into_make_service()) - .await - .unwrap(); + let listener = tokio::net::TcpListener::bind(addr).await.unwrap(); + axum::serve(listener, app).await.unwrap(); } async fn html() -> impl IntoResponse { diff --git a/examples/customize-extractor-error/src/custom_extractor.rs b/examples/customize-extractor-error/src/custom_extractor.rs index 4351384b95..3611fba796 100644 --- a/examples/customize-extractor-error/src/custom_extractor.rs +++ b/examples/customize-extractor-error/src/custom_extractor.rs @@ -6,8 +6,7 @@ //! - Complexity: Manually implementing `FromRequest` results on more complex code use axum::{ async_trait, - extract::{rejection::JsonRejection, FromRequest, MatchedPath}, - http::Request, + extract::{rejection::JsonRejection, FromRequest, MatchedPath, Request}, http::StatusCode, response::IntoResponse, RequestPartsExt, @@ -22,15 +21,14 @@ pub async fn handler(Json(value): Json) -> impl IntoResponse { pub struct Json(pub T); #[async_trait] -impl FromRequest for Json +impl FromRequest for Json where - axum::Json: FromRequest, + axum::Json: FromRequest, S: Send + Sync, - B: Send + 'static, { type Rejection = (StatusCode, axum::Json); - async fn from_request(req: Request, state: &S) -> Result { + async fn from_request(req: Request, state: &S) -> Result { let (mut parts, body) = req.into_parts(); // We can use other extractors to provide better rejection messages. diff --git a/examples/customize-extractor-error/src/main.rs b/examples/customize-extractor-error/src/main.rs index 893fbd148a..e8820326f9 100644 --- a/examples/customize-extractor-error/src/main.rs +++ b/examples/customize-extractor-error/src/main.rs @@ -9,7 +9,6 @@ mod derive_from_request; mod with_rejection; use axum::{routing::post, Router}; -use std::net::SocketAddr; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] @@ -29,10 +28,9 @@ async fn main() { .route("/derive-from-request", post(derive_from_request::handler)); // Run our application - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } diff --git a/examples/customize-path-rejection/src/main.rs b/examples/customize-path-rejection/src/main.rs index 3bcd91d33d..fa382e4bd6 100644 --- a/examples/customize-path-rejection/src/main.rs +++ b/examples/customize-path-rejection/src/main.rs @@ -13,7 +13,6 @@ use axum::{ Router, }; use serde::{de::DeserializeOwned, Deserialize, Serialize}; -use std::net::SocketAddr; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] @@ -30,12 +29,11 @@ async fn main() { let app = Router::new().route("/users/:user_id/teams/:team_id", get(handler)); // run it - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - println!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } async fn handler(Path(params): Path) -> impl IntoResponse { diff --git a/examples/diesel-async-postgres/src/main.rs b/examples/diesel-async-postgres/src/main.rs index 0cb9ba80e2..7403fe459a 100644 --- a/examples/diesel-async-postgres/src/main.rs +++ b/examples/diesel-async-postgres/src/main.rs @@ -77,10 +77,8 @@ async fn main() { // run it with hyper let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) - .await - .unwrap(); + let listener = tokio::net::TcpListener::bind(addr).await.unwrap(); + axum::serve(listener, app).await.unwrap(); } async fn create_user( diff --git a/examples/diesel-postgres/src/main.rs b/examples/diesel-postgres/src/main.rs index 968b1dce4d..9bf9059d57 100644 --- a/examples/diesel-postgres/src/main.rs +++ b/examples/diesel-postgres/src/main.rs @@ -85,10 +85,8 @@ async fn main() { // run it with hyper let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) - .await - .unwrap(); + let listener = tokio::net::TcpListener::bind(addr).await.unwrap(); + axum::serve(listener, app).await.unwrap(); } async fn create_user( diff --git a/examples/error-handling-and-dependency-injection/src/main.rs b/examples/error-handling-and-dependency-injection/src/main.rs index f28ed4ff54..a5bdad9e6f 100644 --- a/examples/error-handling-and-dependency-injection/src/main.rs +++ b/examples/error-handling-and-dependency-injection/src/main.rs @@ -17,7 +17,7 @@ use axum::{ }; use serde::{Deserialize, Serialize}; use serde_json::json; -use std::{net::SocketAddr, sync::Arc}; +use std::sync::Arc; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; use uuid::Uuid; @@ -42,12 +42,11 @@ async fn main() { .with_state(user_repo); // Run our application - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } /// Handler for `GET /users/:id`. diff --git a/examples/form/src/main.rs b/examples/form/src/main.rs index 93a5ae1375..3f9ed09560 100644 --- a/examples/form/src/main.rs +++ b/examples/form/src/main.rs @@ -6,7 +6,6 @@ use axum::{extract::Form, response::Html, routing::get, Router}; use serde::Deserialize; -use std::net::SocketAddr; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] @@ -22,13 +21,12 @@ async fn main() { // build our application with some routes let app = Router::new().route("/", get(show_form).post(accept_form)); - // run it with hyper - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + // run it + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } async fn show_form() -> Html<&'static str> { diff --git a/examples/global-404-handler/src/main.rs b/examples/global-404-handler/src/main.rs index 8eb1469162..38b029439b 100644 --- a/examples/global-404-handler/src/main.rs +++ b/examples/global-404-handler/src/main.rs @@ -10,7 +10,6 @@ use axum::{ routing::get, Router, }; -use std::net::SocketAddr; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] @@ -30,12 +29,11 @@ async fn main() { let app = app.fallback(handler_404); // run it - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } async fn handler() -> Html<&'static str> { diff --git a/examples/graceful-shutdown/Cargo.toml b/examples/graceful-shutdown/Cargo.toml index 19af31136c..f287feeb9c 100644 --- a/examples/graceful-shutdown/Cargo.toml +++ b/examples/graceful-shutdown/Cargo.toml @@ -6,4 +6,5 @@ publish = false [dependencies] axum = { path = "../../axum" } +hyper = { version = "0.14", features = ["full"] } tokio = { version = "1.0", features = ["full"] } diff --git a/examples/graceful-shutdown/src/main.rs b/examples/graceful-shutdown/src/main.rs index 3704889a85..dabfee1697 100644 --- a/examples/graceful-shutdown/src/main.rs +++ b/examples/graceful-shutdown/src/main.rs @@ -17,7 +17,7 @@ async fn main() { // run it let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); println!("listening on {}", addr); - axum::Server::bind(&addr) + hyper::Server::bind(&addr) .serve(app.into_make_service()) .with_graceful_shutdown(shutdown_signal()) .await diff --git a/examples/handle-head-request/src/main.rs b/examples/handle-head-request/src/main.rs index 5b0db2640b..d49d88ef26 100644 --- a/examples/handle-head-request/src/main.rs +++ b/examples/handle-head-request/src/main.rs @@ -6,7 +6,6 @@ use axum::response::{IntoResponse, Response}; use axum::{http, routing::get, Router}; -use std::net::SocketAddr; fn app() -> Router { Router::new().route("/get-head", get(get_head_handler)) @@ -14,12 +13,11 @@ fn app() -> Router { #[tokio::main] async fn main() { - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - - axum::Server::bind(&addr) - .serve(app().into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + println!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app()).await.unwrap(); } // GET routes will also be called for HEAD requests but will have the response body removed. diff --git a/examples/hello-world/src/main.rs b/examples/hello-world/src/main.rs index 466cacebcc..de018335d1 100644 --- a/examples/hello-world/src/main.rs +++ b/examples/hello-world/src/main.rs @@ -5,7 +5,6 @@ //! ``` use axum::{response::Html, routing::get, Router}; -use std::net::SocketAddr; #[tokio::main] async fn main() { @@ -13,12 +12,11 @@ async fn main() { let app = Router::new().route("/", get(handler)); // run it - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - println!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + println!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } async fn handler() -> Html<&'static str> { diff --git a/examples/http-proxy/src/main.rs b/examples/http-proxy/src/main.rs index 27d3b85046..1abf3bbf29 100644 --- a/examples/http-proxy/src/main.rs +++ b/examples/http-proxy/src/main.rs @@ -13,8 +13,9 @@ //! Example is based on use axum::{ - body::{self, Body}, - http::{Method, Request, StatusCode}, + body::Body, + extract::Request, + http::{Method, StatusCode}, response::{IntoResponse, Response}, routing::get, Router, @@ -37,8 +38,9 @@ async fn main() { let router_svc = Router::new().route("/", get(|| async { "Hello, World!" })); - let service = tower::service_fn(move |req: Request| { + let service = tower::service_fn(move |req: Request<_>| { let router_svc = router_svc.clone(); + let req = req.map(Body::new); async move { if req.method() == Method::CONNECT { proxy(req).await @@ -50,7 +52,7 @@ async fn main() { let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) + hyper::Server::bind(&addr) .http1_preserve_header_case(true) .http1_title_case_headers(true) .serve(Shared::new(service)) @@ -58,7 +60,7 @@ async fn main() { .unwrap(); } -async fn proxy(req: Request) -> Result { +async fn proxy(req: Request) -> Result { tracing::trace!(?req); if let Some(host_addr) = req.uri().authority().map(|auth| auth.to_string()) { @@ -73,7 +75,7 @@ async fn proxy(req: Request) -> Result { } }); - Ok(Response::new(body::boxed(body::Empty::new()))) + Ok(Response::new(Body::empty())) } else { tracing::warn!("CONNECT host is not socket addr: {:?}", req.uri()); Ok(( diff --git a/examples/hyper-1-0/src/main.rs b/examples/hyper-1-0/src/main.rs index 72c651cce4..51493d4450 100644 --- a/examples/hyper-1-0/src/main.rs +++ b/examples/hyper-1-0/src/main.rs @@ -8,13 +8,11 @@ use axum::{routing::get, Router}; use std::net::SocketAddr; use tokio::net::TcpListener; use tower_http::trace::TraceLayer; -use tower_hyper_http_body_compat::{ - HttpBody1ToHttpBody04, TowerService03HttpServiceAsHyper1HttpService, -}; +use tower_hyper_http_body_compat::TowerService03HttpServiceAsHyper1HttpService; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; // this is hyper 1.0 -use hyper::{body::Incoming, server::conn::http1}; +use hyper::server::conn::http1; #[tokio::main] async fn main() { @@ -26,8 +24,7 @@ async fn main() { .with(tracing_subscriber::fmt::layer()) .init(); - // you have to use `HttpBody1ToHttpBody04` as the second type parameter to `Router` - let app: Router<_, HttpBody1ToHttpBody04> = Router::new() + let app = Router::new() .route("/", get(|| async { "Hello, World!" })) // we can still add regular tower middleware .layer(TraceLayer::new_for_http()); diff --git a/examples/jwt/Cargo.toml b/examples/jwt/Cargo.toml index a18eb6ec78..b0c76c25d1 100644 --- a/examples/jwt/Cargo.toml +++ b/examples/jwt/Cargo.toml @@ -5,8 +5,8 @@ edition = "2021" publish = false [dependencies] -axum = { path = "../../axum", features = ["headers"] } -headers = "0.3" +axum = { path = "../../axum" } +axum-extra = { path = "../../axum-extra", features = ["typed-header"] } jsonwebtoken = "8.0" once_cell = "1.8" serde = { version = "1.0", features = ["derive"] } diff --git a/examples/jwt/src/main.rs b/examples/jwt/src/main.rs index 4ee20d4bf7..dda09d636e 100644 --- a/examples/jwt/src/main.rs +++ b/examples/jwt/src/main.rs @@ -8,18 +8,21 @@ use axum::{ async_trait, - extract::{FromRequestParts, TypedHeader}, - headers::{authorization::Bearer, Authorization}, + extract::FromRequestParts, http::{request::Parts, StatusCode}, response::{IntoResponse, Response}, routing::{get, post}, Json, RequestPartsExt, Router, }; +use axum_extra::{ + headers::{authorization::Bearer, Authorization}, + TypedHeader, +}; use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Header, Validation}; use once_cell::sync::Lazy; use serde::{Deserialize, Serialize}; use serde_json::json; -use std::{fmt::Display, net::SocketAddr}; +use std::fmt::Display; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; // Quick instructions @@ -67,13 +70,11 @@ async fn main() { .route("/protected", get(protected)) .route("/authorize", post(authorize)); - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } async fn protected(claims: Claims) -> Result { diff --git a/examples/key-value-store/src/main.rs b/examples/key-value-store/src/main.rs index ccf21825db..b22802cb4b 100644 --- a/examples/key-value-store/src/main.rs +++ b/examples/key-value-store/src/main.rs @@ -19,7 +19,6 @@ use axum::{ use std::{ borrow::Cow, collections::HashMap, - net::SocketAddr, sync::{Arc, RwLock}, time::Duration, }; @@ -74,12 +73,11 @@ async fn main() { .with_state(Arc::clone(&shared_state)); // Run our app with hyper - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } type SharedState = Arc>; diff --git a/examples/listen-multiple-addrs/src/main.rs b/examples/listen-multiple-addrs/src/main.rs index f292c1d693..fed70daa1d 100644 --- a/examples/listen-multiple-addrs/src/main.rs +++ b/examples/listen-multiple-addrs/src/main.rs @@ -28,7 +28,7 @@ async fn main() { b: incoming_v6, }; - axum::Server::builder(combined) + hyper::Server::builder(combined) .serve(app.into_make_service()) .await .unwrap(); diff --git a/examples/low-level-openssl/src/main.rs b/examples/low-level-openssl/src/main.rs index 707f6c0a2d..c40e24997c 100644 --- a/examples/low-level-openssl/src/main.rs +++ b/examples/low-level-openssl/src/main.rs @@ -1,7 +1,7 @@ use openssl::ssl::{Ssl, SslAcceptor, SslFiletype, SslMethod}; use tokio_openssl::SslStream; -use axum::{extract::ConnectInfo, routing::get, Router}; +use axum::{body::Body, extract::ConnectInfo, http::Request, routing::get, Router}; use futures_util::future::poll_fn; use hyper::server::{ accept::Accept, @@ -68,7 +68,7 @@ async fn main() { let protocol = protocol.clone(); - let svc = app.make_service(&stream); + let svc = MakeService::<_, Request>::make_service(&mut app, &stream); tokio::spawn(async move { let ssl = Ssl::new(acceptor.context()).unwrap(); diff --git a/examples/low-level-rustls/src/main.rs b/examples/low-level-rustls/src/main.rs index 22176844a5..1e9a951f49 100644 --- a/examples/low-level-rustls/src/main.rs +++ b/examples/low-level-rustls/src/main.rs @@ -4,7 +4,7 @@ //! cargo run -p example-low-level-rustls //! ``` -use axum::{extract::ConnectInfo, routing::get, Router}; +use axum::{extract::ConnectInfo, extract::Request, routing::get, Router}; use futures_util::future::poll_fn; use hyper::server::{ accept::Accept, @@ -24,7 +24,7 @@ use tokio_rustls::{ rustls::{Certificate, PrivateKey, ServerConfig}, TlsAcceptor, }; -use tower::MakeService; +use tower::make::MakeService; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] @@ -53,7 +53,7 @@ async fn main() { let protocol = Arc::new(Http::new()); - let mut app = Router::new() + let mut app = Router::<()>::new() .route("/", get(handler)) .into_make_service_with_connect_info::(); @@ -67,7 +67,7 @@ async fn main() { let protocol = protocol.clone(); - let svc = app.make_service(&stream); + let svc = MakeService::<_, Request>::make_service(&mut app, &stream); tokio::spawn(async move { if let Ok(stream) = acceptor.accept(stream).await { diff --git a/examples/multipart-form/src/main.rs b/examples/multipart-form/src/main.rs index 31f2887e6d..f8c0d96b1c 100644 --- a/examples/multipart-form/src/main.rs +++ b/examples/multipart-form/src/main.rs @@ -10,7 +10,6 @@ use axum::{ routing::get, Router, }; -use std::net::SocketAddr; use tower_http::limit::RequestBodyLimitLayer; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; @@ -34,12 +33,11 @@ async fn main() { .layer(tower_http::trace::TraceLayer::new_for_http()); // run it with hyper - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } async fn show_form() -> Html<&'static str> { diff --git a/examples/oauth/Cargo.toml b/examples/oauth/Cargo.toml index 6613367379..bb0aafc92a 100644 --- a/examples/oauth/Cargo.toml +++ b/examples/oauth/Cargo.toml @@ -6,8 +6,8 @@ publish = false [dependencies] async-session = "3.0.0" -axum = { path = "../../axum", features = ["headers"] } -headers = "0.3" +axum = { path = "../../axum" } +axum-extra = { path = "../../axum-extra", features = ["typed-header"] } http = "0.2" oauth2 = "4.1" # Use Rustls because it makes it easier to cross-compile on CI diff --git a/examples/oauth/src/main.rs b/examples/oauth/src/main.rs index 1a01570f69..ba879e7be8 100644 --- a/examples/oauth/src/main.rs +++ b/examples/oauth/src/main.rs @@ -11,21 +11,20 @@ use async_session::{MemoryStore, Session, SessionStore}; use axum::{ async_trait, - extract::{ - rejection::TypedHeaderRejectionReason, FromRef, FromRequestParts, Query, State, TypedHeader, - }, + extract::{FromRef, FromRequestParts, Query, State}, http::{header::SET_COOKIE, HeaderMap}, response::{IntoResponse, Redirect, Response}, routing::get, RequestPartsExt, Router, }; +use axum_extra::{headers, typed_header::TypedHeaderRejectionReason, TypedHeader}; use http::{header, request::Parts}; use oauth2::{ basic::BasicClient, reqwest::async_http_client, AuthUrl, AuthorizationCode, ClientId, ClientSecret, CsrfToken, RedirectUrl, Scope, TokenResponse, TokenUrl, }; use serde::{Deserialize, Serialize}; -use std::{env, net::SocketAddr}; +use std::env; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; static COOKIE_NAME: &str = "SESSION"; @@ -56,13 +55,11 @@ async fn main() { .route("/logout", get(logout)) .with_state(app_state); - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } #[derive(Clone)] diff --git a/examples/parse-body-based-on-content-type/src/main.rs b/examples/parse-body-based-on-content-type/src/main.rs index 017622380a..bae4ec1d29 100644 --- a/examples/parse-body-based-on-content-type/src/main.rs +++ b/examples/parse-body-based-on-content-type/src/main.rs @@ -8,14 +8,13 @@ use axum::{ async_trait, - extract::FromRequest, - http::{header::CONTENT_TYPE, Request, StatusCode}, + extract::{FromRequest, Request}, + http::{header::CONTENT_TYPE, StatusCode}, response::{IntoResponse, Response}, routing::post, Form, Json, RequestExt, Router, }; use serde::{Deserialize, Serialize}; -use std::net::SocketAddr; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] @@ -31,12 +30,11 @@ async fn main() { let app = Router::new().route("/", post(handler)); - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } #[derive(Debug, Serialize, Deserialize)] @@ -51,17 +49,16 @@ async fn handler(JsonOrForm(payload): JsonOrForm) { struct JsonOrForm(T); #[async_trait] -impl FromRequest for JsonOrForm +impl FromRequest for JsonOrForm where - B: Send + 'static, S: Send + Sync, - Json: FromRequest<(), B>, - Form: FromRequest<(), B>, + Json: FromRequest<()>, + Form: FromRequest<()>, T: 'static, { type Rejection = Response; - async fn from_request(req: Request, _state: &S) -> Result { + async fn from_request(req: Request, _state: &S) -> Result { let content_type_header = req.headers().get(CONTENT_TYPE); let content_type = content_type_header.and_then(|value| value.to_str().ok()); diff --git a/examples/print-request-response/src/main.rs b/examples/print-request-response/src/main.rs index c071ff5495..1348d026d5 100644 --- a/examples/print-request-response/src/main.rs +++ b/examples/print-request-response/src/main.rs @@ -6,13 +6,13 @@ use axum::{ body::{Body, Bytes}, - http::{Request, StatusCode}, + extract::Request, + http::StatusCode, middleware::{self, Next}, response::{IntoResponse, Response}, routing::post, Router, }; -use std::net::SocketAddr; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] @@ -29,17 +29,16 @@ async fn main() { .route("/", post(|| async move { "Hello from `POST /`" })) .layer(middleware::from_fn(print_request_response)); - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } async fn print_request_response( - req: Request, - next: Next, + req: Request, + next: Next, ) -> Result { let (parts, body) = req.into_parts(); let bytes = buffer_and_print("request", body).await?; diff --git a/examples/prometheus-metrics/src/main.rs b/examples/prometheus-metrics/src/main.rs index cf7db5ac29..b90c384f5b 100644 --- a/examples/prometheus-metrics/src/main.rs +++ b/examples/prometheus-metrics/src/main.rs @@ -8,8 +8,7 @@ //! ``` use axum::{ - extract::MatchedPath, - http::Request, + extract::{MatchedPath, Request}, middleware::{self, Next}, response::IntoResponse, routing::get, @@ -18,7 +17,6 @@ use axum::{ use metrics_exporter_prometheus::{Matcher, PrometheusBuilder, PrometheusHandle}; use std::{ future::ready, - net::SocketAddr, time::{Duration, Instant}, }; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; @@ -43,24 +41,22 @@ fn main_app() -> Router { async fn start_main_server() { let app = main_app(); - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await - .unwrap() + .unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } async fn start_metrics_server() { let app = metrics_app(); // NOTE: expose metrics enpoint on a different port - let addr = SocketAddr::from(([127, 0, 0, 1], 3001)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3001") .await - .unwrap() + .unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } #[tokio::main] @@ -94,7 +90,7 @@ fn setup_metrics_recorder() -> PrometheusHandle { .unwrap() } -async fn track_metrics(req: Request, next: Next) -> impl IntoResponse { +async fn track_metrics(req: Request, next: Next) -> impl IntoResponse { let start = Instant::now(); let path = if let Some(matched_path) = req.extensions().get::() { matched_path.as_str().to_owned() diff --git a/examples/query-params-with-empty-strings/src/main.rs b/examples/query-params-with-empty-strings/src/main.rs index aa42464384..19117c4eaa 100644 --- a/examples/query-params-with-empty-strings/src/main.rs +++ b/examples/query-params-with-empty-strings/src/main.rs @@ -10,10 +10,11 @@ use std::{fmt, str::FromStr}; #[tokio::main] async fn main() { - axum::Server::bind(&"0.0.0.0:3000".parse().unwrap()) - .serve(app().into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + println!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app()).await.unwrap(); } fn app() -> Router { diff --git a/examples/readme/src/main.rs b/examples/readme/src/main.rs index bdcb894557..cd2120cb77 100644 --- a/examples/readme/src/main.rs +++ b/examples/readme/src/main.rs @@ -11,7 +11,6 @@ use axum::{ Json, Router, }; use serde::{Deserialize, Serialize}; -use std::net::SocketAddr; #[tokio::main] async fn main() { @@ -26,13 +25,11 @@ async fn main() { .route("/users", post(create_user)); // run our app with hyper - // `axum::Server` is a re-export of `hyper::Server` - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } // basic handler that responds with a static string diff --git a/examples/rest-grpc-multiplex/src/main.rs b/examples/rest-grpc-multiplex/src/main.rs index f804f6ae0c..b7f0ab0237 100644 --- a/examples/rest-grpc-multiplex/src/main.rs +++ b/examples/rest-grpc-multiplex/src/main.rs @@ -75,7 +75,7 @@ async fn main() { let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) + hyper::Server::bind(&addr) .serve(tower::make::Shared::new(service)) .await .unwrap(); diff --git a/examples/rest-grpc-multiplex/src/multiplex_service.rs b/examples/rest-grpc-multiplex/src/multiplex_service.rs index 0f08dbf63f..777c14cd19 100644 --- a/examples/rest-grpc-multiplex/src/multiplex_service.rs +++ b/examples/rest-grpc-multiplex/src/multiplex_service.rs @@ -1,6 +1,9 @@ -use axum::{body::BoxBody, http::header::CONTENT_TYPE, response::IntoResponse}; +use axum::{ + extract::Request, + http::header::CONTENT_TYPE, + response::{IntoResponse, Response}, +}; use futures::{future::BoxFuture, ready}; -use hyper::{Body, Request, Response}; use std::{ convert::Infallible, task::{Context, Poll}, @@ -41,16 +44,16 @@ where } } -impl Service> for MultiplexService +impl Service> for MultiplexService where - A: Service, Error = Infallible>, + A: Service, Error = Infallible>, A::Response: IntoResponse, A::Future: Send + 'static, - B: Service>, + B: Service>, B::Response: IntoResponse, B::Future: Send + 'static, { - type Response = Response; + type Response = Response; type Error = B::Error; type Future = BoxFuture<'static, Result>; @@ -73,7 +76,7 @@ where } } - fn call(&mut self, req: Request) -> Self::Future { + fn call(&mut self, req: Request) -> Self::Future { // require users to call `poll_ready` first, if they don't we're allowed to panic // as per the `tower::Service` contract assert!( diff --git a/examples/reverse-proxy/src/main.rs b/examples/reverse-proxy/src/main.rs index d97dcf44a0..875a3a5a6e 100644 --- a/examples/reverse-proxy/src/main.rs +++ b/examples/reverse-proxy/src/main.rs @@ -8,13 +8,14 @@ //! ``` use axum::{ - extract::State, - http::{uri::Uri, Request, Response}, + body::Body, + extract::{Request, State}, + http::uri::Uri, + response::{IntoResponse, Response}, routing::get, Router, }; -use hyper::{client::HttpConnector, Body}; -use std::net::SocketAddr; +use hyper::client::HttpConnector; type Client = hyper::client::Client; @@ -22,19 +23,18 @@ type Client = hyper::client::Client; async fn main() { tokio::spawn(server()); - let client = Client::new(); + let client: Client = hyper::Client::builder().build(HttpConnector::new()); let app = Router::new().route("/", get(handler)).with_state(client); - let addr = SocketAddr::from(([127, 0, 0, 1], 4000)); - println!("reverse proxy listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:4000") .await .unwrap(); + println!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } -async fn handler(State(client): State, mut req: Request) -> Response { +async fn handler(State(client): State, mut req: Request) -> Response { let path = req.uri().path(); let path_query = req .uri() @@ -46,16 +46,15 @@ async fn handler(State(client): State, mut req: Request) -> Respon *req.uri_mut() = Uri::try_from(uri).unwrap(); - client.request(req).await.unwrap() + client.request(req).await.unwrap().into_response() } async fn server() { let app = Router::new().route("/", get(|| async { "Hello, world!" })); - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - println!("server listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + println!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } diff --git a/examples/routes-and-handlers-close-together/src/main.rs b/examples/routes-and-handlers-close-together/src/main.rs index 75320d095c..50721e700a 100644 --- a/examples/routes-and-handlers-close-together/src/main.rs +++ b/examples/routes-and-handlers-close-together/src/main.rs @@ -8,7 +8,6 @@ use axum::{ routing::{get, post, MethodRouter}, Router, }; -use std::net::SocketAddr; #[tokio::main] async fn main() { @@ -17,12 +16,11 @@ async fn main() { .merge(get_foo()) .merge(post_foo()); - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - println!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + println!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } fn root() -> Router { diff --git a/examples/sessions/Cargo.toml b/examples/sessions/Cargo.toml index 247df4d3c6..bb3d4bda1c 100644 --- a/examples/sessions/Cargo.toml +++ b/examples/sessions/Cargo.toml @@ -6,7 +6,8 @@ publish = false [dependencies] async-session = "3.0.0" -axum = { path = "../../axum", features = ["headers"] } +axum = { path = "../../axum" } +axum-extra = { path = "../../axum-extra", features = ["typed-header"] } serde = { version = "1.0", features = ["derive"] } tokio = { version = "1.0", features = ["full"] } tracing = "0.1" diff --git a/examples/sessions/src/main.rs b/examples/sessions/src/main.rs index 9bea9c1b06..8ee8d9d43e 100644 --- a/examples/sessions/src/main.rs +++ b/examples/sessions/src/main.rs @@ -7,8 +7,7 @@ use async_session::{MemoryStore, Session, SessionStore as _}; use axum::{ async_trait, - extract::{FromRef, FromRequestParts, TypedHeader}, - headers::Cookie, + extract::{FromRef, FromRequestParts}, http::{ self, header::{HeaderMap, HeaderValue}, @@ -19,9 +18,9 @@ use axum::{ routing::get, RequestPartsExt, Router, }; +use axum_extra::{headers::Cookie, TypedHeader}; use serde::{Deserialize, Serialize}; use std::fmt::Debug; -use std::net::SocketAddr; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; use uuid::Uuid; @@ -42,12 +41,11 @@ async fn main() { let app = Router::new().route("/", get(handler)).with_state(store); - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } async fn handler(user_id: UserIdFromSession) -> impl IntoResponse { diff --git a/examples/sqlx-postgres/src/main.rs b/examples/sqlx-postgres/src/main.rs index 8e3353b9a1..e955303798 100644 --- a/examples/sqlx-postgres/src/main.rs +++ b/examples/sqlx-postgres/src/main.rs @@ -21,9 +21,10 @@ use axum::{ Router, }; use sqlx::postgres::{PgPool, PgPoolOptions}; +use tokio::net::TcpListener; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; -use std::{net::SocketAddr, time::Duration}; +use std::time::Duration; #[tokio::main] async fn main() { @@ -55,12 +56,9 @@ async fn main() { .with_state(pool); // run it with hyper - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) - .await - .unwrap(); + let listener = TcpListener::bind("127.0.0.1:3000").await.unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } // we can extract the connection pool with `State` diff --git a/examples/sse/Cargo.toml b/examples/sse/Cargo.toml index c0e12979ff..0131991d8a 100644 --- a/examples/sse/Cargo.toml +++ b/examples/sse/Cargo.toml @@ -5,7 +5,8 @@ edition = "2021" publish = false [dependencies] -axum = { path = "../../axum", features = ["headers"] } +axum = { path = "../../axum" } +axum-extra = { path = "../../axum-extra", features = ["typed-header"] } futures = "0.3" headers = "0.3" tokio = { version = "1.0", features = ["full"] } diff --git a/examples/sse/src/main.rs b/examples/sse/src/main.rs index dab5a565cb..bb60cedf00 100644 --- a/examples/sse/src/main.rs +++ b/examples/sse/src/main.rs @@ -5,13 +5,13 @@ //! ``` use axum::{ - extract::TypedHeader, response::sse::{Event, Sse}, routing::get, Router, }; +use axum_extra::{headers, TypedHeader}; use futures::stream::{self, Stream}; -use std::{convert::Infallible, net::SocketAddr, path::PathBuf, time::Duration}; +use std::{convert::Infallible, path::PathBuf, time::Duration}; use tokio_stream::StreamExt as _; use tower_http::{services::ServeDir, trace::TraceLayer}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; @@ -37,12 +37,11 @@ async fn main() { .layer(TraceLayer::new_for_http()); // run it - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } async fn sse_handler( diff --git a/examples/static-file-server/src/main.rs b/examples/static-file-server/src/main.rs index d1eac21f69..3aa7a9a8fe 100644 --- a/examples/static-file-server/src/main.rs +++ b/examples/static-file-server/src/main.rs @@ -5,11 +5,7 @@ //! ``` use axum::{ - body::Body, - handler::HandlerWithoutStateExt, - http::{Request, StatusCode}, - routing::get, - Router, + extract::Request, handler::HandlerWithoutStateExt, http::StatusCode, routing::get, Router, }; use std::net::SocketAddr; use tower::ServiceExt; @@ -71,7 +67,10 @@ fn using_serve_dir_with_handler_as_service() -> Router { (StatusCode::NOT_FOUND, "Not found") } - let serve_dir = ServeDir::new("assets").not_found_service(handle_404.into_service()); + // you can convert handler function to service + let service = handle_404.into_service(); + + let serve_dir = ServeDir::new("assets").not_found_service(service); Router::new() .route("/foo", get(|| async { "Hi from /foo" })) @@ -94,7 +93,7 @@ fn calling_serve_dir_from_a_handler() -> Router { // call `ServeDir` yourself from a handler Router::new().nest_service( "/foo", - get(|request: Request| async { + get(|request: Request| async { let service = ServeDir::new("assets"); let result = service.oneshot(request).await; result @@ -104,9 +103,9 @@ fn calling_serve_dir_from_a_handler() -> Router { async fn serve(app: Router, port: u16) { let addr = SocketAddr::from(([127, 0, 0, 1], port)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.layer(TraceLayer::new_for_http()).into_make_service()) + let listener = tokio::net::TcpListener::bind(addr).await.unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app.layer(TraceLayer::new_for_http())) .await .unwrap(); } diff --git a/examples/stream-to-file/src/main.rs b/examples/stream-to-file/src/main.rs index 585ad3de6c..02164d4e50 100644 --- a/examples/stream-to-file/src/main.rs +++ b/examples/stream-to-file/src/main.rs @@ -6,14 +6,14 @@ use axum::{ body::Bytes, - extract::{BodyStream, Multipart, Path}, + extract::{Multipart, Path, Request}, http::StatusCode, response::{Html, Redirect}, routing::{get, post}, BoxError, Router, }; use futures::{Stream, TryStreamExt}; -use std::{io, net::SocketAddr}; +use std::io; use tokio::{fs::File, io::BufWriter}; use tokio_util::io::StreamReader; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; @@ -39,12 +39,11 @@ async fn main() { .route("/", get(show_form).post(accept_form)) .route("/file/:file_name", post(save_request_body)); - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } // Handler that streams the request body to a file. @@ -52,9 +51,9 @@ async fn main() { // POST'ing to `/file/foo.txt` will create a file called `foo.txt`. async fn save_request_body( Path(file_name): Path, - body: BodyStream, + request: Request, ) -> Result<(), (StatusCode, String)> { - stream_to_file(&file_name, body).await + stream_to_file(&file_name, request.into_body()).await } // Handler that returns HTML for a multipart form. diff --git a/examples/templates/src/main.rs b/examples/templates/src/main.rs index d7e01a944b..1abdb33eb3 100644 --- a/examples/templates/src/main.rs +++ b/examples/templates/src/main.rs @@ -12,7 +12,6 @@ use axum::{ routing::get, Router, }; -use std::net::SocketAddr; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] @@ -29,12 +28,11 @@ async fn main() { let app = Router::new().route("/greet/:name", get(greet)); // run it - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } async fn greet(extract::Path(name): extract::Path) -> impl IntoResponse { diff --git a/examples/testing-websockets/src/main.rs b/examples/testing-websockets/src/main.rs index b778115c9f..954168b170 100644 --- a/examples/testing-websockets/src/main.rs +++ b/examples/testing-websockets/src/main.rs @@ -14,16 +14,14 @@ use axum::{ Router, }; use futures::{Sink, SinkExt, Stream, StreamExt}; -use std::net::SocketAddr; #[tokio::main] async fn main() { - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - println!("listening on {addr}"); - axum::Server::bind(&addr) - .serve(app().into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + println!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app()).await.unwrap(); } fn app() -> Router { @@ -94,17 +92,18 @@ where #[cfg(test)] mod tests { use super::*; - use std::net::Ipv4Addr; + use std::net::{Ipv4Addr, SocketAddr}; use tokio_tungstenite::tungstenite; // We can integration test one handler by running the server in a background task and // connecting to it like any other client would. #[tokio::test] async fn integration_test() { - let server = axum::Server::bind(&SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0))) - .serve(app().into_make_service()); - let addr = server.local_addr(); - tokio::spawn(server); + let listener = tokio::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0))) + .await + .unwrap(); + let addr = listener.local_addr().unwrap(); + tokio::spawn(axum::serve(listener, app())); let (mut socket, _response) = tokio_tungstenite::connect_async(format!("ws://{addr}/integration-testable")) diff --git a/examples/testing/src/main.rs b/examples/testing/src/main.rs index b5f7466b46..99cc0402cf 100644 --- a/examples/testing/src/main.rs +++ b/examples/testing/src/main.rs @@ -24,14 +24,11 @@ async fn main() { .with(tracing_subscriber::fmt::layer()) .init(); - let addr = std::net::SocketAddr::from(([127, 0, 0, 1], 3000)); - - tracing::debug!("listening on {}", addr); - - axum::Server::bind(&addr) - .serve(app().into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app()).await.unwrap(); } /// Having a function that produces our app makes it easy to call it from tests @@ -63,7 +60,8 @@ mod tests { http::{self, Request, StatusCode}, }; use serde_json::{json, Value}; - use std::net::{SocketAddr, TcpListener}; + use std::net::SocketAddr; + use tokio::net::TcpListener; use tower::Service; // for `call` use tower::ServiceExt; // for `oneshot` and `ready` @@ -131,15 +129,11 @@ mod tests { // You can also spawn a server and talk to it like any other HTTP server: #[tokio::test] async fn the_real_deal() { - let listener = TcpListener::bind("0.0.0.0:0".parse::().unwrap()).unwrap(); + let listener = TcpListener::bind("0.0.0.0:0").await.unwrap(); let addr = listener.local_addr().unwrap(); tokio::spawn(async move { - axum::Server::from_tcp(listener) - .unwrap() - .serve(app().into_make_service()) - .await - .unwrap(); + axum::serve(listener, app()).await.unwrap(); }); let client = hyper::Client::new(); @@ -148,7 +142,7 @@ mod tests { .request( Request::builder() .uri(format!("http://{}", addr)) - .body(Body::empty()) + .body(hyper::Body::empty()) .unwrap(), ) .await @@ -162,14 +156,24 @@ mod tests { // in multiple request #[tokio::test] async fn multiple_request() { - let mut app = app(); + let mut app = app().into_service(); let request = Request::builder().uri("/").body(Body::empty()).unwrap(); - let response = app.ready().await.unwrap().call(request).await.unwrap(); + let response = ServiceExt::>::ready(&mut app) + .await + .unwrap() + .call(request) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::OK); let request = Request::builder().uri("/").body(Body::empty()).unwrap(); - let response = app.ready().await.unwrap().call(request).await.unwrap(); + let response = ServiceExt::>::ready(&mut app) + .await + .unwrap() + .call(request) + .await + .unwrap(); assert_eq!(response.status(), StatusCode::OK); } @@ -180,7 +184,9 @@ mod tests { // tests. #[tokio::test] async fn with_into_make_service_with_connect_info() { - let mut app = app().layer(MockConnectInfo(SocketAddr::from(([0, 0, 0, 0], 3000)))); + let mut app = app() + .layer(MockConnectInfo(SocketAddr::from(([0, 0, 0, 0], 3000)))) + .into_service(); let request = Request::builder() .uri("/requires-connect-into") diff --git a/examples/tls-rustls/src/main.rs b/examples/tls-rustls/src/main.rs index 5034cf31e7..860f56b5ee 100644 --- a/examples/tls-rustls/src/main.rs +++ b/examples/tls-rustls/src/main.rs @@ -93,10 +93,9 @@ async fn redirect_http_to_https(ports: Ports) { }; let addr = SocketAddr::from(([127, 0, 0, 1], ports.http)); - tracing::debug!("http redirect listening on {}", addr); - - axum::Server::bind(&addr) - .serve(redirect.into_make_service()) + let listener = tokio::net::TcpListener::bind(addr).await.unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, redirect.into_make_service()) .await .unwrap(); } diff --git a/examples/todos/src/main.rs b/examples/todos/src/main.rs index 4463bfa44a..9e08876d8c 100644 --- a/examples/todos/src/main.rs +++ b/examples/todos/src/main.rs @@ -24,7 +24,6 @@ use axum::{ use serde::{Deserialize, Serialize}; use std::{ collections::HashMap, - net::SocketAddr, sync::{Arc, RwLock}, time::Duration, }; @@ -68,12 +67,11 @@ async fn main() { ) .with_state(db); - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } // The query parameters for todos index diff --git a/examples/tokio-postgres/src/main.rs b/examples/tokio-postgres/src/main.rs index 77c4c112b5..effc032089 100644 --- a/examples/tokio-postgres/src/main.rs +++ b/examples/tokio-postgres/src/main.rs @@ -13,7 +13,6 @@ use axum::{ }; use bb8::{Pool, PooledConnection}; use bb8_postgres::PostgresConnectionManager; -use std::net::SocketAddr; use tokio_postgres::NoTls; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; @@ -41,13 +40,12 @@ async fn main() { ) .with_state(pool); - // run it with hyper - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + // run it + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } type ConnectionPool = Pool>; diff --git a/examples/tracing-aka-logging/src/main.rs b/examples/tracing-aka-logging/src/main.rs index 6b4524ac64..74a2055a07 100644 --- a/examples/tracing-aka-logging/src/main.rs +++ b/examples/tracing-aka-logging/src/main.rs @@ -12,7 +12,8 @@ use axum::{ routing::get, Router, }; -use std::{net::SocketAddr, time::Duration}; +use std::time::Duration; +use tokio::net::TcpListener; use tower_http::{classify::ServerErrorsFailureClass, trace::TraceLayer}; use tracing::{info_span, Span}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; @@ -80,12 +81,9 @@ async fn main() { ); // run it - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) - .await - .unwrap(); + let listener = TcpListener::bind("127.0.0.1:3000").await.unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } async fn handler() -> Html<&'static str> { diff --git a/examples/unix-domain-socket/src/main.rs b/examples/unix-domain-socket/src/main.rs index 0a3d3f0d47..ce350720c0 100644 --- a/examples/unix-domain-socket/src/main.rs +++ b/examples/unix-domain-socket/src/main.rs @@ -63,7 +63,7 @@ mod unix { tokio::spawn(async { let app = Router::new().route("/", get(handler)); - axum::Server::builder(ServerAccept { uds }) + hyper::Server::builder(ServerAccept { uds }) .serve(app.into_make_service_with_connect_info::()) .await .unwrap(); diff --git a/examples/validator/src/main.rs b/examples/validator/src/main.rs index ecfe9509d3..a6a25b8566 100644 --- a/examples/validator/src/main.rs +++ b/examples/validator/src/main.rs @@ -12,15 +12,15 @@ use async_trait::async_trait; use axum::{ - extract::{rejection::FormRejection, Form, FromRequest}, - http::{Request, StatusCode}, + extract::{rejection::FormRejection, Form, FromRequest, Request}, + http::StatusCode, response::{Html, IntoResponse, Response}, routing::get, Router, }; use serde::{de::DeserializeOwned, Deserialize}; -use std::net::SocketAddr; use thiserror::Error; +use tokio::net::TcpListener; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; use validator::Validate; @@ -38,13 +38,9 @@ async fn main() { let app = Router::new().route("/", get(handler)); // run it - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - - axum::Server::bind(&addr) - .serve(app.into_make_service()) - .await - .unwrap(); + let listener = TcpListener::bind("127.0.0.1:3000").await.unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } #[derive(Debug, Deserialize, Validate)] @@ -61,16 +57,15 @@ async fn handler(ValidatedForm(input): ValidatedForm) -> Html pub struct ValidatedForm(pub T); #[async_trait] -impl FromRequest for ValidatedForm +impl FromRequest for ValidatedForm where T: DeserializeOwned + Validate, S: Send + Sync, - Form: FromRequest, - B: Send + 'static, + Form: FromRequest, { type Rejection = ServerError; - async fn from_request(req: Request, state: &S) -> Result { + async fn from_request(req: Request, state: &S) -> Result { let Form(value) = Form::::from_request(req, state).await?; value.validate()?; Ok(ValidatedForm(value)) diff --git a/examples/versioning/src/main.rs b/examples/versioning/src/main.rs index fd3f66682a..b5324d69f4 100644 --- a/examples/versioning/src/main.rs +++ b/examples/versioning/src/main.rs @@ -12,7 +12,7 @@ use axum::{ routing::get, RequestPartsExt, Router, }; -use std::{collections::HashMap, net::SocketAddr}; +use std::collections::HashMap; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] @@ -29,12 +29,11 @@ async fn main() { let app = Router::new().route("/:version/foo", get(handler)); // run it - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve(listener, app).await.unwrap(); } async fn handler(version: Version) { diff --git a/examples/websockets/Cargo.toml b/examples/websockets/Cargo.toml index 30e6c3c0f1..c385b78944 100644 --- a/examples/websockets/Cargo.toml +++ b/examples/websockets/Cargo.toml @@ -5,7 +5,8 @@ edition = "2021" publish = false [dependencies] -axum = { path = "../../axum", features = ["ws", "headers"] } +axum = { path = "../../axum", features = ["ws"] } +axum-extra = { path = "../../axum-extra", features = ["typed-header"] } futures = "0.3" futures-util = { version = "0.3", default-features = false, features = ["sink", "std"] } headers = "0.3" diff --git a/examples/websockets/src/main.rs b/examples/websockets/src/main.rs index 73993c15f3..1a7a9bd46e 100644 --- a/examples/websockets/src/main.rs +++ b/examples/websockets/src/main.rs @@ -17,14 +17,12 @@ //! ``` use axum::{ - extract::{ - ws::{Message, WebSocket, WebSocketUpgrade}, - TypedHeader, - }, + extract::ws::{Message, WebSocket, WebSocketUpgrade}, response::IntoResponse, routing::get, Router, }; +use axum_extra::TypedHeader; use std::borrow::Cow; use std::ops::ControlFlow; @@ -66,12 +64,16 @@ async fn main() { ); // run it with hyper - let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); - tracing::debug!("listening on {}", addr); - axum::Server::bind(&addr) - .serve(app.into_make_service_with_connect_info::()) + let listener = tokio::net::TcpListener::bind("127.0.0.1:3000") .await .unwrap(); + tracing::debug!("listening on {}", listener.local_addr().unwrap()); + axum::serve( + listener, + app.into_make_service_with_connect_info::(), + ) + .await + .unwrap(); } /// The handler for the HTTP request (this gets called when the HTTP GET lands at the start