repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum/src/test_helpers/test_client.rs
axum/src/test_helpers/test_client.rs
use super::{serve, Request, Response}; use bytes::Bytes; use futures_core::future::BoxFuture; use http::header::{HeaderName, HeaderValue}; use std::ops::Deref; use std::{convert::Infallible, future::IntoFuture, net::SocketAddr}; use tokio::net::TcpListener; use tower::make::Shared; use tower_service::Service; pub(crate) fn spawn_service<S>(svc: S) -> SocketAddr where S: Service<Request, Response = Response, Error = Infallible> + Clone + Send + 'static, S::Future: Send, { 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 { serve(listener, Shared::new(svc)).await; }); addr } pub struct TestClient { client: reqwest::Client, addr: SocketAddr, } impl TestClient { pub fn new<S>(svc: S) -> Self where S: Service<Request, Response = Response, Error = Infallible> + Clone + Send + 'static, S::Future: Send, { let addr = spawn_service(svc); let client = reqwest::Client::builder() .redirect(reqwest::redirect::Policy::none()) .build() .unwrap(); Self { client, addr } } pub fn get(&self, url: &str) -> RequestBuilder { RequestBuilder { builder: self.client.get(format!("http://{}{url}", self.addr)), } } pub fn head(&self, url: &str) -> RequestBuilder { RequestBuilder { builder: self.client.head(format!("http://{}{url}", self.addr)), } } pub fn post(&self, url: &str) -> RequestBuilder { RequestBuilder { builder: self.client.post(format!("http://{}{url}", self.addr)), } } #[allow(dead_code)] pub fn put(&self, url: &str) -> RequestBuilder { RequestBuilder { builder: self.client.put(format!("http://{}{url}", self.addr)), } } #[allow(dead_code)] pub fn patch(&self, url: &str) -> RequestBuilder { RequestBuilder { builder: self.client.patch(format!("http://{}{url}", self.addr)), } } #[allow(dead_code)] #[must_use] pub fn server_port(&self) -> u16 { self.addr.port() } } #[must_use] pub struct RequestBuilder { builder: reqwest::RequestBuilder, } impl RequestBuilder { pub fn body(mut self, body: impl Into<reqwest::Body>) -> Self { self.builder = self.builder.body(body); self } pub fn json<T>(mut self, json: &T) -> Self where T: serde_core::Serialize, { self.builder = self.builder.json(json); self } pub fn header<K, V>(mut self, key: K, value: V) -> Self where HeaderName: TryFrom<K>, <HeaderName as TryFrom<K>>::Error: Into<http::Error>, HeaderValue: TryFrom<V>, <HeaderValue as TryFrom<V>>::Error: Into<http::Error>, { self.builder = self.builder.header(key, value); self } #[allow(dead_code)] pub fn multipart(mut self, form: reqwest::multipart::Form) -> Self { self.builder = self.builder.multipart(form); self } } impl IntoFuture for RequestBuilder { type Output = TestResponse; type IntoFuture = BoxFuture<'static, Self::Output>; fn into_future(self) -> Self::IntoFuture { Box::pin(async { TestResponse { response: self.builder.send().await.unwrap(), } }) } } #[derive(Debug)] pub struct TestResponse { response: reqwest::Response, } impl Deref for TestResponse { type Target = reqwest::Response; fn deref(&self) -> &Self::Target { &self.response } } impl TestResponse { #[allow(dead_code)] pub async fn bytes(self) -> Bytes { self.response.bytes().await.unwrap() } pub async fn text(self) -> String { self.response.text().await.unwrap() } #[allow(dead_code)] pub async fn json<T>(self) -> T where T: serde_core::de::DeserializeOwned, { self.response.json().await.unwrap() } pub async fn chunk(&mut self) -> Option<Bytes> { self.response.chunk().await.unwrap() } pub async fn chunk_text(&mut self) -> Option<String> { let chunk = self.chunk().await?; Some(String::from_utf8(chunk.to_vec()).unwrap()) } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum/src/test_helpers/mod.rs
axum/src/test_helpers/mod.rs
#![allow(clippy::disallowed_names)] use crate::{extract::Request, response::Response, serve}; mod test_client; pub use self::test_client::*; #[cfg(test)] pub(crate) mod tracing_helpers; #[cfg(test)] pub(crate) mod counting_cloneable_state; #[cfg(test)] pub(crate) fn assert_send<T: Send>() {} #[cfg(test)] pub(crate) fn assert_sync<T: Sync>() {} #[allow(dead_code)] pub(crate) struct NotSendSync(*const ());
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum/src/test_helpers/counting_cloneable_state.rs
axum/src/test_helpers/counting_cloneable_state.rs
use std::sync::{ atomic::{AtomicBool, AtomicUsize, Ordering}, Arc, }; pub(crate) struct CountingCloneableState { state: Arc<InnerState>, } struct InnerState { setup_done: AtomicBool, count: AtomicUsize, } impl CountingCloneableState { pub(crate) fn new() -> Self { let inner_state = InnerState { setup_done: AtomicBool::new(false), count: AtomicUsize::new(0), }; Self { state: Arc::new(inner_state), } } pub(crate) fn setup_done(&self) { self.state.setup_done.store(true, Ordering::SeqCst); } pub(crate) fn count(&self) -> usize { self.state.count.load(Ordering::SeqCst) } } impl Clone for CountingCloneableState { fn clone(&self) -> Self { let state = self.state.clone(); if state.setup_done.load(Ordering::SeqCst) { let bt = std::backtrace::Backtrace::force_capture(); let bt = bt .to_string() .lines() .filter(|line| line.contains("axum") || line.contains("./src")) .collect::<Vec<_>>() .join("\n"); println!("AppState::Clone:\n===============\n{bt}\n"); state.count.fetch_add(1, Ordering::SeqCst); } Self { state } } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum/src/body/mod.rs
axum/src/body/mod.rs
//! HTTP body utilities. #[doc(no_inline)] pub use http_body::Body as HttpBody; #[doc(no_inline)] pub use bytes::Bytes; #[doc(inline)] pub use axum_core::body::{Body, BodyDataStream}; use http_body_util::{BodyExt, Limited}; /// Converts [`Body`] into [`Bytes`] and limits the maximum size of the body. /// /// # Example /// /// ```rust /// use axum::body::{to_bytes, Body}; /// /// # async fn foo() -> Result<(), axum_core::Error> { /// let body = Body::from(vec![1, 2, 3]); /// // Use `usize::MAX` if you don't care about the maximum size. /// let bytes = to_bytes(body, usize::MAX).await?; /// assert_eq!(&bytes[..], &[1, 2, 3]); /// # Ok(()) /// # } /// ``` /// /// You can detect if the limit was hit by checking the source of the error: /// /// ```rust /// use axum::body::{to_bytes, Body}; /// use http_body_util::LengthLimitError; /// /// # #[tokio::main] /// # async fn main() { /// let body = Body::from(vec![1, 2, 3]); /// match to_bytes(body, 1).await { /// Ok(_bytes) => panic!("should have hit the limit"), /// Err(err) => { /// let source = std::error::Error::source(&err).unwrap(); /// assert!(source.is::<LengthLimitError>()); /// } /// } /// # } /// ``` pub async fn to_bytes(body: Body, limit: usize) -> Result<Bytes, axum_core::Error> { Limited::new(body, limit) .collect() .await .map(|col| col.to_bytes()) .map_err(axum_core::Error::new) }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum/src/error_handling/mod.rs
axum/src/error_handling/mod.rs
#![doc = include_str!("../docs/error_handling.md")] use crate::{ extract::FromRequestParts, http::Request, response::{IntoResponse, Response}, }; use std::{ convert::Infallible, fmt, future::Future, marker::PhantomData, task::{Context, Poll}, }; use tower::ServiceExt; use tower_layer::Layer; use tower_service::Service; /// [`Layer`] that applies [`HandleError`] which is a [`Service`] adapter /// that handles errors by converting them into responses. /// /// See [module docs](self) for more details on axum's error handling model. pub struct HandleErrorLayer<F, T> { f: F, _extractor: PhantomData<fn() -> T>, } impl<F, T> HandleErrorLayer<F, T> { /// Create a new `HandleErrorLayer`. pub fn new(f: F) -> Self { Self { f, _extractor: PhantomData, } } } impl<F, T> Clone for HandleErrorLayer<F, T> where F: Clone, { fn clone(&self) -> Self { Self { f: self.f.clone(), _extractor: PhantomData, } } } impl<F, E> fmt::Debug for HandleErrorLayer<F, E> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("HandleErrorLayer") .field("f", &format_args!("{}", std::any::type_name::<F>())) .finish() } } impl<S, F, T> Layer<S> for HandleErrorLayer<F, T> where F: Clone, { type Service = HandleError<S, F, T>; fn layer(&self, inner: S) -> Self::Service { HandleError::new(inner, self.f.clone()) } } /// A [`Service`] adapter that handles errors by converting them into responses. /// /// See [module docs](self) for more details on axum's error handling model. pub struct HandleError<S, F, T> { inner: S, f: F, _extractor: PhantomData<fn() -> T>, } impl<S, F, T> HandleError<S, F, T> { /// Create a new `HandleError`. pub fn new(inner: S, f: F) -> Self { Self { inner, f, _extractor: PhantomData, } } } impl<S, F, T> Clone for HandleError<S, F, T> where S: Clone, F: Clone, { fn clone(&self) -> Self { Self { inner: self.inner.clone(), f: self.f.clone(), _extractor: PhantomData, } } } impl<S, F, E> fmt::Debug for HandleError<S, F, E> where S: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("HandleError") .field("inner", &self.inner) .field("f", &format_args!("{}", std::any::type_name::<F>())) .finish() } } impl<S, F, B, Fut, Res> Service<Request<B>> for HandleError<S, F, ()> where S: Service<Request<B>> + Clone + Send + 'static, S::Response: IntoResponse + Send, S::Error: Send, S::Future: Send, F: FnOnce(S::Error) -> Fut + Clone + Send + 'static, Fut: Future<Output = Res> + Send, Res: IntoResponse, B: Send + 'static, { type Response = Response; type Error = Infallible; type Future = future::HandleErrorFuture; fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Poll::Ready(Ok(())) } fn call(&mut self, req: Request<B>) -> Self::Future { let f = self.f.clone(); let clone = self.inner.clone(); let inner = std::mem::replace(&mut self.inner, clone); let future = Box::pin(async move { match inner.oneshot(req).await { Ok(res) => Ok(res.into_response()), Err(err) => Ok(f(err).await.into_response()), } }); future::HandleErrorFuture { future } } } #[allow(unused_macros)] macro_rules! impl_service { ( $($ty:ident),* $(,)? ) => { impl<S, F, B, Res, Fut, $($ty,)*> Service<Request<B>> for HandleError<S, F, ($($ty,)*)> where S: Service<Request<B>> + Clone + Send + 'static, S::Response: IntoResponse + Send, S::Error: Send, S::Future: Send, F: FnOnce($($ty),*, S::Error) -> Fut + Clone + Send + 'static, Fut: Future<Output = Res> + Send, Res: IntoResponse, $( $ty: FromRequestParts<()> + Send,)* B: Send + 'static, { type Response = Response; type Error = Infallible; type Future = future::HandleErrorFuture; fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Poll::Ready(Ok(())) } #[allow(non_snake_case)] fn call(&mut self, req: Request<B>) -> Self::Future { let f = self.f.clone(); let clone = self.inner.clone(); let inner = std::mem::replace(&mut self.inner, clone); let (mut parts, body) = req.into_parts(); let future = Box::pin(async move { $( let $ty = match $ty::from_request_parts(&mut parts, &()).await { Ok(value) => value, Err(rejection) => return Ok(rejection.into_response()), }; )* let req = Request::from_parts(parts, body); match inner.oneshot(req).await { Ok(res) => Ok(res.into_response()), Err(err) => Ok(f($($ty),*, err).await.into_response()), } }); future::HandleErrorFuture { future } } } } } impl_service!(T1); impl_service!(T1, T2); impl_service!(T1, T2, T3); impl_service!(T1, T2, T3, T4); impl_service!(T1, T2, T3, T4, T5); impl_service!(T1, T2, T3, T4, T5, T6); impl_service!(T1, T2, T3, T4, T5, T6, T7); impl_service!(T1, T2, T3, T4, T5, T6, T7, T8); impl_service!(T1, T2, T3, T4, T5, T6, T7, T8, T9); impl_service!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10); impl_service!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11); impl_service!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12); impl_service!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13); impl_service!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14); impl_service!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15); impl_service!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16); pub mod future { //! Future types. use crate::response::Response; use pin_project_lite::pin_project; use std::{ convert::Infallible, future::Future, pin::Pin, task::{Context, Poll}, }; pin_project! { /// Response future for [`HandleError`]. pub struct HandleErrorFuture { #[pin] pub(super) future: Pin<Box<dyn Future<Output = Result<Response, Infallible>> + Send + 'static >>, } } impl Future for HandleErrorFuture { type Output = Result<Response, Infallible>; fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { self.project().future.poll(cx) } } } #[test] fn traits() { use crate::test_helpers::*; assert_send::<HandleError<(), (), NotSendSync>>(); assert_sync::<HandleError<(), (), NotSendSync>>(); }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum/src/handler/future.rs
axum/src/handler/future.rs
//! Handler future types. use crate::response::Response; use axum_core::extract::Request; use futures_util::future::Map; use pin_project_lite::pin_project; use std::{convert::Infallible, future::Future, pin::Pin, task::Context}; use tower::util::Oneshot; use tower_service::Service; opaque_future! { /// The response future for [`IntoService`](super::IntoService). pub type IntoServiceFuture<F> = Map< F, fn(Response) -> Result<Response, Infallible>, >; } pin_project! { /// The response future for [`Layered`](super::Layered). pub struct LayeredFuture<S> where S: Service<Request>, { #[pin] inner: Map<Oneshot<S, Request>, fn(Result<S::Response, S::Error>) -> Response>, } } impl<S> LayeredFuture<S> where S: Service<Request>, { pub(super) fn new( inner: Map<Oneshot<S, Request>, fn(Result<S::Response, S::Error>) -> Response>, ) -> Self { Self { inner } } } impl<S> Future for LayeredFuture<S> where S: Service<Request>, { type Output = Response; #[inline] fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> std::task::Poll<Self::Output> { self.project().inner.poll(cx) } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum/src/handler/service.rs
axum/src/handler/service.rs
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, fmt, marker::PhantomData, task::{Context, Poll}, }; use tower_service::Service; /// An adapter that makes a [`Handler`] into a [`Service`]. /// /// Created with [`Handler::with_state`] or [`HandlerWithoutStateExt::into_service`]. /// /// [`HandlerWithoutStateExt::into_service`]: super::HandlerWithoutStateExt::into_service pub struct HandlerService<H, T, S> { handler: H, state: S, _marker: PhantomData<fn() -> T>, } impl<H, T, S> HandlerService<H, T, S> { /// Get a reference to the state. pub fn state(&self) -> &S { &self.state } /// Convert the handler into a [`MakeService`]. /// /// This allows you to serve a single handler if you don't need any routing: /// /// ```rust /// use axum::{ /// handler::Handler, /// extract::State, /// http::{Uri, Method}, /// response::IntoResponse, /// }; /// use std::net::SocketAddr; /// /// #[derive(Clone)] /// struct AppState {} /// /// async fn handler(State(state): State<AppState>) { /// // ... /// } /// /// let app = handler.with_state(AppState {}); /// /// # async { /// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); /// axum::serve(listener, app.into_make_service()).await; /// # }; /// ``` /// /// [`MakeService`]: tower::make::MakeService pub fn into_make_service(self) -> IntoMakeService<Self> { IntoMakeService::new(self) } /// Convert the handler into a [`MakeService`] which stores information /// about the incoming connection. /// /// See [`Router::into_make_service_with_connect_info`] for more details. /// /// ```rust /// use axum::{ /// handler::Handler, /// response::IntoResponse, /// extract::{ConnectInfo, State}, /// }; /// use std::net::SocketAddr; /// /// #[derive(Clone)] /// struct AppState {}; /// /// async fn handler( /// ConnectInfo(addr): ConnectInfo<SocketAddr>, /// State(state): State<AppState>, /// ) -> String { /// format!("Hello {addr}") /// } /// /// let app = handler.with_state(AppState {}); /// /// # async { /// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); /// axum::serve( /// listener, /// app.into_make_service_with_connect_info::<SocketAddr>(), /// ).await; /// # }; /// ``` /// /// [`MakeService`]: tower::make::MakeService /// [`Router::into_make_service_with_connect_info`]: crate::routing::Router::into_make_service_with_connect_info #[cfg(feature = "tokio")] pub fn into_make_service_with_connect_info<C>(self) -> IntoMakeServiceWithConnectInfo<Self, C> { IntoMakeServiceWithConnectInfo::new(self) } } #[test] fn traits() { use crate::test_helpers::*; assert_send::<HandlerService<(), NotSendSync, ()>>(); assert_sync::<HandlerService<(), NotSendSync, ()>>(); } impl<H, T, S> HandlerService<H, T, S> { pub(super) fn new(handler: H, state: S) -> Self { Self { handler, state, _marker: PhantomData, } } } impl<H, T, S> fmt::Debug for HandlerService<H, T, S> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("IntoService").finish_non_exhaustive() } } impl<H, T, S> Clone for HandlerService<H, T, S> where H: Clone, S: Clone, { fn clone(&self) -> Self { Self { handler: self.handler.clone(), state: self.state.clone(), _marker: PhantomData, } } } impl<H, T, S, B> Service<Request<B>> for HandlerService<H, T, S> where H: Handler<T, S> + Clone + Send + 'static, B: HttpBody<Data = Bytes> + Send + 'static, B::Error: Into<BoxError>, S: Clone + Send + Sync, { type Response = Response; type Error = Infallible; type Future = super::future::IntoServiceFuture<H::Future>; #[inline] fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { // `IntoService` can only be constructed from async functions which are always ready, or // from `Layered` which buffers in `<Layered as Handler>::call` and is therefore // also always ready. Poll::Ready(Ok(())) } fn call(&mut self, req: Request<B>) -> 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 _); super::future::IntoServiceFuture::new(future) } } // for `axum::serve(listener, handler)` #[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))] const _: () = { use crate::serve; impl<H, T, S, L> Service<serve::IncomingStream<'_, L>> for HandlerService<H, T, S> where H: Clone, S: Clone, L: serve::Listener, { type Response = Self; type Error = Infallible; type Future = std::future::Ready<Result<Self::Response, Self::Error>>; fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Poll::Ready(Ok(())) } fn call(&mut self, _req: serve::IncomingStream<'_, L>) -> Self::Future { std::future::ready(Ok(self.clone())) } } };
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum/src/handler/mod.rs
axum/src/handler/mod.rs
//! Async functions that can be used to handle requests. //! #![doc = include_str!("../docs/handlers_intro.md")] //! //! Some examples of handlers: //! //! ```rust //! use axum::{body::Bytes, http::StatusCode}; //! //! // Handler that immediately returns an empty `200 OK` response. //! async fn unit_handler() {} //! //! // Handler that immediately returns a `200 OK` response with a plain text //! // body. //! async fn string_handler() -> String { //! "Hello, World!".to_string() //! } //! //! // Handler that buffers the request body and returns it. //! // //! // This works because `Bytes` implements `FromRequest` //! // and therefore can be used as an extractor. //! // //! // `String` and `StatusCode` both implement `IntoResponse` and //! // therefore `Result<String, StatusCode>` also implements `IntoResponse` //! async fn echo(body: Bytes) -> Result<String, StatusCode> { //! if let Ok(string) = String::from_utf8(body.to_vec()) { //! Ok(string) //! } else { //! Err(StatusCode::BAD_REQUEST) //! } //! } //! ``` //! //! Instead of a direct `StatusCode`, it makes sense to use intermediate error type //! that can ultimately be converted to `Response`. This allows using `?` operator //! in handlers. See those examples: //! //! * [`anyhow-error-response`][anyhow] for generic boxed errors //! * [`error-handling`][error-handling] for application-specific detailed errors //! //! [anyhow]: https://github.com/tokio-rs/axum/blob/main/examples/anyhow-error-response/src/main.rs //! [error-handling]: https://github.com/tokio-rs/axum/blob/main/examples/error-handling/src/main.rs //! #![doc = include_str!("../docs/debugging_handler_type_errors.md")] #[cfg(feature = "tokio")] use crate::extract::connect_info::IntoMakeServiceWithConnectInfo; use crate::{ extract::{FromRequest, FromRequestParts, Request}, response::{IntoResponse, Response}, routing::IntoMakeService, }; use std::{convert::Infallible, fmt, future::Future, marker::PhantomData, pin::Pin}; use tower::ServiceExt; use tower_layer::Layer; use tower_service::Service; pub mod future; mod service; pub use self::service::HandlerService; /// Trait for async functions that can be used to handle requests. /// /// You shouldn't need to depend on this trait directly. It is automatically /// implemented to closures of the right types. /// /// See the [module docs](crate::handler) for more details. /// /// # Converting `Handler`s into [`Service`]s /// /// To convert `Handler`s into [`Service`]s you have to call either /// [`HandlerWithoutStateExt::into_service`] or [`Handler::with_state`]: /// /// ``` /// use tower::Service; /// use axum::{ /// extract::{State, Request}, /// body::Body, /// handler::{HandlerWithoutStateExt, Handler}, /// }; /// /// // this handler doesn't require any state /// async fn one() {} /// // so it can be converted to a service with `HandlerWithoutStateExt::into_service` /// assert_service(one.into_service()); /// /// // this handler requires state /// async fn two(_: State<String>) {} /// // so we have to provide it /// let handler_with_state = two.with_state(String::new()); /// // which gives us a `Service` /// assert_service(handler_with_state); /// /// // helper to check that a value implements `Service` /// fn assert_service<S>(service: S) /// where /// S: Service<Request>, /// {} /// ``` #[doc = include_str!("../docs/debugging_handler_type_errors.md")] /// /// # Handlers that aren't functions /// /// The `Handler` trait is also implemented for `T: IntoResponse`. That allows easily returning /// fixed data for routes: /// /// ``` /// use axum::{ /// Router, /// routing::{get, post}, /// Json, /// http::StatusCode, /// }; /// use serde_json::json; /// /// let app = Router::new() /// // respond with a fixed string /// .route("/", get("Hello, World!")) /// // or return some mock data /// .route("/users", post(( /// StatusCode::CREATED, /// Json(json!({ "id": 1, "username": "alice" })), /// ))); /// # let _: Router = app; /// ``` /// /// # About type parameter `T` /// /// **Generally you shouldn't need to worry about `T`**; when calling methods such as /// [`post`](crate::routing::method_routing::post) it will be automatically inferred and this is /// the intended way for this parameter to be provided in application code. /// /// If you are implementing your own methods that accept implementations of `Handler` as /// arguments, then the following may be useful: /// /// The type parameter `T` is a workaround for trait coherence rules, allowing us to /// write blanket implementations of `Handler` over many types of handler functions /// with different numbers of arguments, without the compiler forbidding us from doing /// so because one type `F` can in theory implement both `Fn(A) -> X` and `Fn(A, B) -> Y`. /// `T` is a placeholder taking on a representation of the parameters of the handler function, /// as well as other similar 'coherence rule workaround' discriminators, /// allowing us to select one function signature to use as a `Handler`. #[diagnostic::on_unimplemented( note = "Consider using `#[axum::debug_handler]` to improve the error message" )] pub trait Handler<T, S>: Clone + Send + Sync + Sized + 'static { /// The type of future calling this handler returns. type Future: Future<Output = Response> + Send + 'static; /// Call the handler with the given request. fn call(self, req: Request, state: S) -> Self::Future; /// Apply a [`tower::Layer`] to the handler. /// /// All requests to the handler will be processed by the layer's /// corresponding middleware. /// /// This can be used to add additional processing to a request for a single /// handler. /// /// Note this differs from [`routing::Router::layer`](crate::routing::Router::layer) /// which adds a middleware to a group of routes. /// /// If you're applying middleware that produces errors you have to handle the errors /// so they're converted into responses. You can learn more about doing that /// [here](crate::error_handling). /// /// # Example /// /// Adding the [`tower::limit::ConcurrencyLimit`] middleware to a handler /// can be done like so: /// /// ```rust /// use axum::{ /// routing::get, /// handler::Handler, /// Router, /// }; /// use tower::limit::{ConcurrencyLimitLayer, ConcurrencyLimit}; /// /// async fn handler() { /* ... */ } /// /// let layered_handler = handler.layer(ConcurrencyLimitLayer::new(64)); /// let app = Router::new().route("/", get(layered_handler)); /// # let _: Router = app; /// ``` fn layer<L>(self, layer: L) -> Layered<L, Self, T, S> where L: Layer<HandlerService<Self, T, S>> + Clone, L::Service: Service<Request>, { Layered { layer, handler: self, _marker: PhantomData, } } /// Convert the handler into a [`Service`] by providing the state fn with_state(self, state: S) -> HandlerService<Self, T, S> { HandlerService::new(self, state) } } #[diagnostic::do_not_recommend] impl<F, Fut, Res, S> Handler<((),), S> for F where F: FnOnce() -> Fut + Clone + Send + Sync + 'static, Fut: Future<Output = Res> + Send, Res: IntoResponse, { type Future = Pin<Box<dyn Future<Output = Response> + Send>>; fn call(self, _req: Request, _state: S) -> Self::Future { Box::pin(async move { self().await.into_response() }) } } macro_rules! impl_handler { ( [$($ty:ident),*], $last:ident ) => { #[diagnostic::do_not_recommend] #[allow(non_snake_case, unused_mut)] impl<F, Fut, S, Res, M, $($ty,)* $last> Handler<(M, $($ty,)* $last,), S> for F where F: FnOnce($($ty,)* $last,) -> Fut + Clone + Send + Sync + 'static, Fut: Future<Output = Res> + Send, S: Send + Sync + 'static, Res: IntoResponse, $( $ty: FromRequestParts<S> + Send, )* $last: FromRequest<S, M> + Send, { type Future = Pin<Box<dyn Future<Output = Response> + Send>>; fn call(self, req: Request, state: S) -> Self::Future { let (mut parts, body) = req.into_parts(); Box::pin(async move { $( let $ty = match $ty::from_request_parts(&mut parts, &state).await { Ok(value) => value, Err(rejection) => return rejection.into_response(), }; )* let req = Request::from_parts(parts, body); let $last = match $last::from_request(req, &state).await { Ok(value) => value, Err(rejection) => return rejection.into_response(), }; self($($ty,)* $last,).await.into_response() }) } } }; } all_the_tuples!(impl_handler); mod private { // Marker type for `impl<T: IntoResponse> Handler for T` #[allow(missing_debug_implementations)] pub enum IntoResponseHandler {} } #[diagnostic::do_not_recommend] impl<T, S> Handler<private::IntoResponseHandler, S> for T where T: IntoResponse + Clone + Send + Sync + 'static, { type Future = std::future::Ready<Response>; fn call(self, _req: Request, _state: S) -> Self::Future { std::future::ready(self.into_response()) } } /// A [`Service`] created from a [`Handler`] by applying a Tower middleware. /// /// Created with [`Handler::layer`]. See that method for more details. pub struct Layered<L, H, T, S> { layer: L, handler: H, _marker: PhantomData<fn() -> (T, S)>, } impl<L, H, T, S> fmt::Debug for Layered<L, H, T, S> where L: fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Layered") .field("layer", &self.layer) .finish() } } impl<L, H, T, S> Clone for Layered<L, H, T, S> where L: Clone, H: Clone, { fn clone(&self) -> Self { Self { layer: self.layer.clone(), handler: self.handler.clone(), _marker: PhantomData, } } } #[diagnostic::do_not_recommend] impl<H, S, T, L> Handler<T, S> for Layered<L, H, T, S> where L: Layer<HandlerService<H, T, S>> + Clone + Send + Sync + 'static, H: Handler<T, S>, L::Service: Service<Request, Error = Infallible> + Clone + Send + 'static, <L::Service as Service<Request>>::Response: IntoResponse, <L::Service as Service<Request>>::Future: Send, T: 'static, S: 'static, { type Future = future::LayeredFuture<L::Service>; fn call(self, req: Request, state: S) -> Self::Future { use futures_util::future::{FutureExt, Map}; let svc = self.handler.with_state(state); let svc = self.layer.layer(svc); let future: Map< _, fn( Result< <L::Service as Service<Request>>::Response, <L::Service as Service<Request>>::Error, >, ) -> _, > = svc.oneshot(req).map(|result| match result { Ok(res) => res.into_response(), Err(err) => match err {}, }); future::LayeredFuture::new(future) } } /// Extension trait for [`Handler`]s that don't have state. /// /// This provides convenience methods to convert the [`Handler`] into a [`Service`] or [`MakeService`]. /// /// [`MakeService`]: tower::make::MakeService pub trait HandlerWithoutStateExt<T>: Handler<T, ()> { /// Convert the handler into a [`Service`] and no state. fn into_service(self) -> HandlerService<Self, T, ()>; /// 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<HandlerService<Self, T, ()>>; /// Convert the handler into a [`MakeService`] which stores information /// about the incoming connection and has no state. /// /// See [`HandlerService::into_make_service_with_connect_info`] for more details. /// /// [`MakeService`]: tower::make::MakeService #[cfg(feature = "tokio")] fn into_make_service_with_connect_info<C>( self, ) -> IntoMakeServiceWithConnectInfo<HandlerService<Self, T, ()>, C>; } impl<H, T> HandlerWithoutStateExt<T> for H where H: Handler<T, ()>, { fn into_service(self) -> HandlerService<Self, T, ()> { self.with_state(()) } fn into_make_service(self) -> IntoMakeService<HandlerService<Self, T, ()>> { self.into_service().into_make_service() } #[cfg(feature = "tokio")] fn into_make_service_with_connect_info<C>( self, ) -> IntoMakeServiceWithConnectInfo<HandlerService<Self, T, ()>, C> { self.into_service().into_make_service_with_connect_info() } } #[cfg(test)] mod tests { use super::*; use crate::{extract::State, test_helpers::*}; use axum_core::body::Body; use http::StatusCode; use std::time::Duration; use tower_http::{ limit::RequestBodyLimitLayer, map_request_body::MapRequestBodyLayer, map_response_body::MapResponseBodyLayer, timeout::TimeoutLayer, }; #[crate::test] async fn handler_into_service() { async fn handle(body: String) -> impl IntoResponse { format!("you said: {body}") } let client = TestClient::new(handle.into_service()); let res = client.post("/").body("hi there!").await; assert_eq!(res.status(), StatusCode::OK); assert_eq!(res.text().await, "you said: hi there!"); } #[crate::test] async fn with_layer_that_changes_request_body_and_state() { async fn handle(State(state): State<&'static str>) -> &'static str { state } let svc = handle .layer(( RequestBodyLimitLayer::new(1024), TimeoutLayer::new(Duration::from_secs(10)), MapResponseBodyLayer::new(Body::new), )) .layer(MapRequestBodyLayer::new(Body::new)) .with_state("foo"); let client = TestClient::new(svc); let res = client.get("/").await; assert_eq!(res.text().await, "foo"); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum/src/serve/listener.rs
axum/src/serve/listener.rs
use std::{ fmt, future::Future, pin::Pin, sync::Arc, task::{Context, Poll}, time::Duration, }; use pin_project_lite::pin_project; use tokio::{ io::{self, AsyncRead, AsyncWrite}, net::{TcpListener, TcpStream}, sync::{OwnedSemaphorePermit, Semaphore}, }; /// Types that can listen for connections. pub trait Listener: Send + 'static { /// The listener's IO type. type Io: AsyncRead + AsyncWrite + Unpin + Send + 'static; /// The listener's address type. type Addr: Send; /// Accept a new incoming connection to this listener. /// /// If the underlying accept call can return an error, this function must /// take care of logging and retrying. fn accept(&mut self) -> impl Future<Output = (Self::Io, Self::Addr)> + Send; /// Returns the local address that this listener is bound to. fn local_addr(&self) -> io::Result<Self::Addr>; } impl Listener for TcpListener { type Io = TcpStream; type Addr = std::net::SocketAddr; async fn accept(&mut self) -> (Self::Io, Self::Addr) { loop { match Self::accept(self).await { Ok(tup) => return tup, Err(e) => handle_accept_error(e).await, } } } #[inline] fn local_addr(&self) -> io::Result<Self::Addr> { Self::local_addr(self) } } #[cfg(unix)] impl Listener for tokio::net::UnixListener { type Io = tokio::net::UnixStream; type Addr = tokio::net::unix::SocketAddr; async fn accept(&mut self) -> (Self::Io, Self::Addr) { loop { match Self::accept(self).await { Ok(tup) => return tup, Err(e) => handle_accept_error(e).await, } } } #[inline] fn local_addr(&self) -> io::Result<Self::Addr> { Self::local_addr(self) } } /// Extensions to [`Listener`]. pub trait ListenerExt: Listener + Sized { /// Limit the number of concurrent connections. Once the limit has /// been reached, no additional connections will be accepted until /// an existing connection is closed. Listener implementations will /// typically continue to queue incoming connections, up to an OS /// and implementation-specific listener backlog limit. /// /// Compare [`tower::limit::concurrency`], which provides ways to /// limit concurrent in-flight requests, but does not limit connections /// that are idle or in the process of sending request headers. /// /// [`tower::limit::concurrency`]: https://docs.rs/tower/latest/tower/limit/concurrency/ fn limit_connections(self, limit: usize) -> ConnLimiter<Self> { ConnLimiter { listener: self, sem: Arc::new(Semaphore::new(limit)), } } /// Run a mutable closure on every accepted `Io`. /// /// # Example /// /// ``` /// use axum::{Router, routing::get, serve::ListenerExt}; /// use tracing::trace; /// /// # async { /// let router = Router::new().route("/", get(|| async { "Hello, World!" })); /// /// let listener = tokio::net::TcpListener::bind("0.0.0.0:3000") /// .await /// .unwrap() /// .tap_io(|tcp_stream| { /// if let Err(err) = tcp_stream.set_nodelay(true) { /// trace!("failed to set TCP_NODELAY on incoming connection: {err:#}"); /// } /// }); /// axum::serve(listener, router).await; /// # }; /// ``` fn tap_io<F>(self, tap_fn: F) -> TapIo<Self, F> where F: FnMut(&mut Self::Io) + Send + 'static, { TapIo { listener: self, tap_fn, } } } impl<L: Listener> ListenerExt for L {} /// Return type of [`ListenerExt::limit_connections`]. /// /// See that method for details. #[derive(Debug)] pub struct ConnLimiter<T> { listener: T, sem: Arc<Semaphore>, } impl<T: Listener> Listener for ConnLimiter<T> { type Io = ConnLimiterIo<T::Io>; type Addr = T::Addr; async fn accept(&mut self) -> (Self::Io, Self::Addr) { let permit = self.sem.clone().acquire_owned().await.unwrap(); let (io, addr) = self.listener.accept().await; (ConnLimiterIo { io, permit }, addr) } fn local_addr(&self) -> tokio::io::Result<Self::Addr> { self.listener.local_addr() } } pin_project! { /// A connection counted by [`ConnLimiter`]. /// /// See [`ListenerExt::limit_connections`] for details. #[derive(Debug)] pub struct ConnLimiterIo<T> { #[pin] io: T, permit: OwnedSemaphorePermit, } } // Simply forward implementation to `io` field. impl<T: AsyncRead> AsyncRead for ConnLimiterIo<T> { fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut io::ReadBuf<'_>, ) -> Poll<io::Result<()>> { self.project().io.poll_read(cx, buf) } } // Simply forward implementation to `io` field. impl<T: AsyncWrite> AsyncWrite for ConnLimiterIo<T> { fn is_write_vectored(&self) -> bool { self.io.is_write_vectored() } fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> { self.project().io.poll_flush(cx) } fn poll_shutdown(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<io::Result<()>> { self.project().io.poll_shutdown(cx) } fn poll_write( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<io::Result<usize>> { self.project().io.poll_write(cx, buf) } fn poll_write_vectored( self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[std::io::IoSlice<'_>], ) -> Poll<io::Result<usize>> { self.project().io.poll_write_vectored(cx, bufs) } } /// Return type of [`ListenerExt::tap_io`]. /// /// See that method for details. pub struct TapIo<L, F> { listener: L, tap_fn: F, } impl<L, F> fmt::Debug for TapIo<L, F> where L: Listener + fmt::Debug, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("TapIo") .field("listener", &self.listener) .finish_non_exhaustive() } } impl<L, F> Listener for TapIo<L, F> where L: Listener, F: FnMut(&mut L::Io) + Send + 'static, { type Io = L::Io; type Addr = L::Addr; async fn accept(&mut self) -> (Self::Io, Self::Addr) { let (mut io, addr) = self.listener.accept().await; (self.tap_fn)(&mut io); (io, addr) } fn local_addr(&self) -> io::Result<Self::Addr> { self.listener.local_addr() } } async fn handle_accept_error(e: io::Error) { if is_connection_error(&e) { return; } // [From `hyper::Server` in 0.14](https://github.com/hyperium/hyper/blob/v0.14.27/src/server/tcp.rs#L186) // // > A possible scenario is that the process has hit the max open files // > allowed, and so trying to accept a new connection will fail with // > `EMFILE`. In some cases, it's preferable to just wait for some time, if // > the application will likely close some files (or connections), and try // > to accept the connection again. If this option is `true`, the error // > will be logged at the `error` level, since it is still a big deal, // > and then the listener will sleep for 1 second. // // hyper allowed customizing this but axum does not. error!("accept error: {e}"); tokio::time::sleep(Duration::from_secs(1)).await; } fn is_connection_error(e: &io::Error) -> bool { matches!( e.kind(), io::ErrorKind::ConnectionRefused | io::ErrorKind::ConnectionAborted | io::ErrorKind::ConnectionReset ) } #[cfg(test)] mod tests { use std::sync::atomic::{AtomicUsize, Ordering}; use tokio::{io, time}; use super::{Listener, ListenerExt}; #[tokio::test(start_paused = true)] async fn limit_connections() { static COUNT: AtomicUsize = AtomicUsize::new(0); struct MyListener; impl Listener for MyListener { type Io = io::DuplexStream; type Addr = (); async fn accept(&mut self) -> (Self::Io, Self::Addr) { COUNT.fetch_add(1, Ordering::SeqCst); (io::duplex(0).0, ()) // dummy connection } fn local_addr(&self) -> io::Result<Self::Addr> { Ok(()) } } let mut listener = MyListener.limit_connections(1); assert_eq!(COUNT.load(Ordering::SeqCst), 0); // First 'accept' succeeds immediately. let conn1 = listener.accept().await; assert_eq!(COUNT.load(Ordering::SeqCst), 1); time::timeout(time::Duration::from_secs(1), listener.accept()) .await .expect_err("Second 'accept' should time out."); // It never reaches MyListener::accept to be counted. assert_eq!(COUNT.load(Ordering::SeqCst), 1); // Close the first connection. drop(conn1); // Now 'accept' again succeeds immediately. let _conn2 = listener.accept().await; assert_eq!(COUNT.load(Ordering::SeqCst), 2); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum/src/serve/mod.rs
axum/src/serve/mod.rs
//! Serve services. use std::{ convert::Infallible, error::Error as StdError, fmt::Debug, future::{Future, IntoFuture}, io, marker::PhantomData, pin::pin, }; use axum_core::{body::Body, extract::Request, response::Response}; use futures_util::FutureExt; use http_body::Body as HttpBody; use hyper::body::Incoming; use hyper_util::rt::{TokioExecutor, TokioIo, TokioTimer}; #[cfg(any(feature = "http1", feature = "http2"))] use hyper_util::{server::conn::auto::Builder, service::TowerToHyperService}; use tokio::sync::watch; use tower::ServiceExt as _; use tower_service::Service; mod listener; pub use self::listener::{ConnLimiter, ConnLimiterIo, Listener, ListenerExt, TapIo}; /// Serve the service with the supplied listener. /// /// This method of running a service is intentionally simple and doesn't support any configuration. /// hyper's default configuration applies (including [timeouts]); use hyper or hyper-util if you /// need configuration. /// /// It supports both HTTP/1 as well as HTTP/2. /// /// # 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; /// # }; /// ``` /// /// 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; /// # }; /// ``` /// /// 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; /// # }; /// ``` /// /// See also [`HandlerWithoutStateExt::into_make_service_with_connect_info`] and /// [`HandlerService::into_make_service_with_connect_info`]. /// /// # Return Value /// /// Although this future resolves to `io::Result<()>`, it will never actually complete or return an /// error. Errors on the TCP socket will be handled by sleeping for a short while (currently, one /// second). /// /// [timeouts]: hyper::server::conn::http1::Builder::header_read_timeout /// [`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(all(feature = "tokio", any(feature = "http1", feature = "http2")))] pub fn serve<L, M, S, B>(listener: L, make_service: M) -> Serve<L, M, S, B> where L: Listener, M: for<'a> Service<IncomingStream<'a, L>, Error = Infallible, Response = S>, S: Service<Request, Response = Response<B>, Error = Infallible> + Clone + Send + 'static, S::Future: Send, B: HttpBody + Send + 'static, B::Data: Send, B::Error: Into<Box<dyn StdError + Send + Sync>>, { Serve { listener, make_service, _marker: PhantomData, } } /// Future returned by [`serve`]. #[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))] #[must_use = "futures must be awaited or polled"] pub struct Serve<L, M, S, B> { listener: L, make_service: M, _marker: PhantomData<fn(B) -> S>, } #[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))] impl<L, M, S, B> Serve<L, M, S, B> where L: Listener, { /// Prepares a server to handle graceful shutdown when the provided future completes. /// /// # Example /// /// ``` /// 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) /// .with_graceful_shutdown(shutdown_signal()) /// .await; /// # }; /// /// async fn shutdown_signal() { /// // ... /// } /// ``` /// /// # Return Value /// /// Similarly to [`serve`], although this future resolves to `io::Result<()>`, it will never /// error. It returns `Ok(())` only after the `signal` future completes. pub fn with_graceful_shutdown<F>(self, signal: F) -> WithGracefulShutdown<L, M, S, F, B> where F: Future<Output = ()> + Send + 'static, { WithGracefulShutdown { listener: self.listener, make_service: self.make_service, signal, _marker: PhantomData, } } /// Returns the local address this server is bound to. pub fn local_addr(&self) -> io::Result<L::Addr> { self.listener.local_addr() } } #[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))] impl<L, M, S, B> Serve<L, M, S, B> where L: Listener, L::Addr: Debug, M: for<'a> Service<IncomingStream<'a, L>, Error = Infallible, Response = S> + Send + 'static, for<'a> <M as Service<IncomingStream<'a, L>>>::Future: Send, S: Service<Request, Response = Response<B>, Error = Infallible> + Clone + Send + 'static, S::Future: Send, B: HttpBody + Send + 'static, B::Data: Send, B::Error: Into<Box<dyn StdError + Send + Sync>>, { async fn run(self) -> ! { let Self { mut listener, mut make_service, _marker, } = self; let (signal_tx, _signal_rx) = watch::channel(()); let (_close_tx, close_rx) = watch::channel(()); loop { let (io, remote_addr) = listener.accept().await; handle_connection(&mut make_service, &signal_tx, &close_rx, io, remote_addr).await; } } } #[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))] impl<L, M, S, B> Debug for Serve<L, M, S, B> where L: Debug + 'static, M: Debug, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let Self { listener, make_service, _marker: _, } = self; let mut s = f.debug_struct("Serve"); s.field("listener", listener) .field("make_service", make_service); s.finish() } } #[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))] impl<L, M, S, B> IntoFuture for Serve<L, M, S, B> where L: Listener, L::Addr: Debug, M: for<'a> Service<IncomingStream<'a, L>, Error = Infallible, Response = S> + Send + 'static, for<'a> <M as Service<IncomingStream<'a, L>>>::Future: Send, S: Service<Request, Response = Response<B>, Error = Infallible> + Clone + Send + 'static, S::Future: Send, B: HttpBody + Send + 'static, B::Data: Send, B::Error: Into<Box<dyn StdError + Send + Sync>>, { type Output = Infallible; type IntoFuture = private::ServeFuture; fn into_future(self) -> Self::IntoFuture { private::ServeFuture(Box::pin(async move { self.run().await })) } } /// Serve future with graceful shutdown enabled. #[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))] #[must_use = "futures must be awaited or polled"] pub struct WithGracefulShutdown<L, M, S, F, B> { listener: L, make_service: M, signal: F, _marker: PhantomData<fn(B) -> S>, } #[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))] impl<L, M, S, F, B> WithGracefulShutdown<L, M, S, F, B> where L: Listener, { /// Returns the local address this server is bound to. pub fn local_addr(&self) -> io::Result<L::Addr> { self.listener.local_addr() } } #[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))] impl<L, M, S, F, B> WithGracefulShutdown<L, M, S, F, B> where L: Listener, L::Addr: Debug, M: for<'a> Service<IncomingStream<'a, L>, Error = Infallible, Response = S> + Send + 'static, for<'a> <M as Service<IncomingStream<'a, L>>>::Future: Send, S: Service<Request, Response = Response<B>, Error = Infallible> + Clone + Send + 'static, S::Future: Send, F: Future<Output = ()> + Send + 'static, B: HttpBody + Send + 'static, B::Data: Send, B::Error: Into<Box<dyn StdError + Send + Sync>>, { async fn run(self) { let Self { mut listener, mut make_service, signal, _marker, } = self; let (signal_tx, signal_rx) = watch::channel(()); tokio::spawn(async move { signal.await; trace!("received graceful shutdown signal. Telling tasks to shutdown"); drop(signal_rx); }); let (close_tx, close_rx) = watch::channel(()); loop { let (io, remote_addr) = tokio::select! { conn = listener.accept() => conn, _ = signal_tx.closed() => { trace!("signal received, not accepting new connections"); break; } }; handle_connection(&mut make_service, &signal_tx, &close_rx, io, remote_addr).await; } drop(close_rx); drop(listener); trace!( "waiting for {} task(s) to finish", close_tx.receiver_count() ); close_tx.closed().await; } } #[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))] impl<L, M, S, F, B> Debug for WithGracefulShutdown<L, M, S, F, B> where L: Debug + 'static, M: Debug, S: Debug, F: Debug, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let Self { listener, make_service, signal, _marker: _, } = self; f.debug_struct("WithGracefulShutdown") .field("listener", listener) .field("make_service", make_service) .field("signal", signal) .finish() } } #[cfg(all(feature = "tokio", any(feature = "http1", feature = "http2")))] impl<L, M, S, F, B> IntoFuture for WithGracefulShutdown<L, M, S, F, B> where L: Listener, L::Addr: Debug, M: for<'a> Service<IncomingStream<'a, L>, Error = Infallible, Response = S> + Send + 'static, for<'a> <M as Service<IncomingStream<'a, L>>>::Future: Send, S: Service<Request, Response = Response<B>, Error = Infallible> + Clone + Send + 'static, S::Future: Send, F: Future<Output = ()> + Send + 'static, B: HttpBody + Send + 'static, B::Data: Send, B::Error: Into<Box<dyn StdError + Send + Sync>>, { type Output = (); type IntoFuture = private::ServeFuture<()>; fn into_future(self) -> Self::IntoFuture { private::ServeFuture(Box::pin(async move { self.run().await })) } } async fn handle_connection<L, M, S, B>( make_service: &mut M, signal_tx: &watch::Sender<()>, close_rx: &watch::Receiver<()>, io: <L as Listener>::Io, remote_addr: <L as Listener>::Addr, ) where L: Listener, L::Addr: Debug, M: for<'a> Service<IncomingStream<'a, L>, Error = Infallible, Response = S> + Send + 'static, for<'a> <M as Service<IncomingStream<'a, L>>>::Future: Send, S: Service<Request, Response = Response<B>, Error = Infallible> + Clone + Send + 'static, S::Future: Send, B: HttpBody + Send + 'static, B::Data: Send, B::Error: Into<Box<dyn StdError + Send + Sync>>, { let io = TokioIo::new(io); trace!("connection {remote_addr:?} accepted"); make_service .ready() .await .unwrap_or_else(|err| match err {}); let tower_service = make_service .call(IncomingStream { io: &io, remote_addr, }) .await .unwrap_or_else(|err| match err {}) .map_request(|req: Request<Incoming>| req.map(Body::new)); let hyper_service = TowerToHyperService::new(tower_service); let signal_tx = signal_tx.clone(); let close_rx = close_rx.clone(); tokio::spawn(async move { #[allow(unused_mut)] let mut builder = Builder::new(TokioExecutor::new()); // Enable Hyper's default HTTP/1 request header timeout. #[cfg(feature = "http1")] builder.http1().timer(TokioTimer::new()); // CONNECT protocol needed for HTTP/2 websockets #[cfg(feature = "http2")] builder.http2().enable_connect_protocol(); let mut conn = pin!(builder.serve_connection_with_upgrades(io, hyper_service)); let mut signal_closed = pin!(signal_tx.closed().fuse()); loop { tokio::select! { result = conn.as_mut() => { if let Err(_err) = result { trace!("failed to serve connection: {_err:#}"); } break; } _ = &mut signal_closed => { trace!("signal received in task, starting graceful shutdown"); conn.as_mut().graceful_shutdown(); } } } drop(close_rx); }); } /// An incoming stream. /// /// Used with [`serve`] and [`IntoMakeServiceWithConnectInfo`]. /// /// [`IntoMakeServiceWithConnectInfo`]: crate::extract::connect_info::IntoMakeServiceWithConnectInfo #[derive(Debug)] pub struct IncomingStream<'a, L> where L: Listener, { io: &'a TokioIo<L::Io>, remote_addr: L::Addr, } impl<L> IncomingStream<'_, L> where L: Listener, { /// Get a reference to the inner IO type. pub fn io(&self) -> &L::Io { self.io.inner() } /// Returns the remote address that this stream is bound to. pub fn remote_addr(&self) -> &L::Addr { &self.remote_addr } } mod private { use std::{ convert::Infallible, future::Future, pin::Pin, task::{Context, Poll}, }; pub struct ServeFuture<T = Infallible>(pub(super) futures_core::future::BoxFuture<'static, T>); impl<T> Future for ServeFuture<T> { type Output = T; #[inline] fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { self.0.as_mut().poll(cx) } } impl std::fmt::Debug for ServeFuture { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("ServeFuture").finish_non_exhaustive() } } } #[cfg(test)] mod tests { use std::{ future::{pending, IntoFuture as _}, net::{IpAddr, Ipv4Addr}, time::Duration, }; use axum_core::{body::Body, extract::Request}; use http::{Response, StatusCode}; use hyper_util::rt::TokioIo; #[cfg(unix)] use tokio::net::UnixListener; use tokio::{ io::{self, AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt}, net::TcpListener, }; use tower::ServiceBuilder; #[cfg(unix)] use super::IncomingStream; use super::{serve, Listener}; #[cfg(unix)] use crate::extract::connect_info::Connected; use crate::{ body::to_bytes, handler::{Handler, HandlerWithoutStateExt}, routing::get, serve::ListenerExt, Router, ServiceExt, }; struct ReadyListener<T>(Option<T>); impl<T> Listener for ReadyListener<T> where T: AsyncRead + AsyncWrite + Unpin + Send + 'static, { type Io = T; type Addr = (); async fn accept(&mut self) -> (Self::Io, Self::Addr) { match self.0.take() { Some(server) => (server, ()), None => std::future::pending().await, } } fn local_addr(&self) -> io::Result<Self::Addr> { Ok(()) } } #[allow(dead_code, unused_must_use)] async fn if_it_compiles_it_works() { #[derive(Clone, Debug)] struct UdsConnectInfo; #[cfg(unix)] impl Connected<IncomingStream<'_, UnixListener>> for UdsConnectInfo { fn connect_info(_stream: IncomingStream<'_, UnixListener>) -> Self { Self } } let router: Router = Router::new(); let addr = "0.0.0.0:0"; let tcp_nodelay_listener = || async { TcpListener::bind(addr).await.unwrap().tap_io(|tcp_stream| { if let Err(err) = tcp_stream.set_nodelay(true) { eprintln!("failed to set TCP_NODELAY on incoming connection: {err:#}"); } }) }; // router serve(TcpListener::bind(addr).await.unwrap(), router.clone()); serve(tcp_nodelay_listener().await, router.clone()).await; #[cfg(unix)] serve(UnixListener::bind("").unwrap(), router.clone()); serve( TcpListener::bind(addr).await.unwrap(), router.clone().into_make_service(), ); serve( tcp_nodelay_listener().await, router.clone().into_make_service(), ); #[cfg(unix)] serve( UnixListener::bind("").unwrap(), router.clone().into_make_service(), ); serve( TcpListener::bind(addr).await.unwrap(), router .clone() .into_make_service_with_connect_info::<std::net::SocketAddr>(), ); serve( tcp_nodelay_listener().await, router .clone() .into_make_service_with_connect_info::<std::net::SocketAddr>(), ); #[cfg(unix)] serve( UnixListener::bind("").unwrap(), router.into_make_service_with_connect_info::<UdsConnectInfo>(), ); // method router serve(TcpListener::bind(addr).await.unwrap(), get(handler)); serve(tcp_nodelay_listener().await, get(handler)); #[cfg(unix)] serve(UnixListener::bind("").unwrap(), get(handler)); serve( TcpListener::bind(addr).await.unwrap(), get(handler).into_make_service(), ); serve( tcp_nodelay_listener().await, get(handler).into_make_service(), ); #[cfg(unix)] serve( UnixListener::bind("").unwrap(), get(handler).into_make_service(), ); serve( TcpListener::bind(addr).await.unwrap(), get(handler).into_make_service_with_connect_info::<std::net::SocketAddr>(), ); serve( tcp_nodelay_listener().await, get(handler).into_make_service_with_connect_info::<std::net::SocketAddr>(), ); #[cfg(unix)] serve( UnixListener::bind("").unwrap(), get(handler).into_make_service_with_connect_info::<UdsConnectInfo>(), ); // handler serve( TcpListener::bind(addr).await.unwrap(), handler.into_service(), ); serve(tcp_nodelay_listener().await, handler.into_service()); #[cfg(unix)] serve(UnixListener::bind("").unwrap(), handler.into_service()); serve( TcpListener::bind(addr).await.unwrap(), handler.with_state(()), ); serve(tcp_nodelay_listener().await, handler.with_state(())); #[cfg(unix)] serve(UnixListener::bind("").unwrap(), handler.with_state(())); serve( TcpListener::bind(addr).await.unwrap(), handler.into_make_service(), ); serve(tcp_nodelay_listener().await, handler.into_make_service()); #[cfg(unix)] serve(UnixListener::bind("").unwrap(), handler.into_make_service()); serve( TcpListener::bind(addr).await.unwrap(), handler.into_make_service_with_connect_info::<std::net::SocketAddr>(), ); serve( tcp_nodelay_listener().await, handler.into_make_service_with_connect_info::<std::net::SocketAddr>(), ); #[cfg(unix)] serve( UnixListener::bind("").unwrap(), handler.into_make_service_with_connect_info::<UdsConnectInfo>(), ); } async fn handler() {} #[crate::test] async fn test_serve_local_addr() { let router: Router = Router::new(); let addr = "0.0.0.0:0"; let server = serve(TcpListener::bind(addr).await.unwrap(), router.clone()); let address = server.local_addr().unwrap(); assert_eq!(address.ip(), IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0))); assert_ne!(address.port(), 0); } #[crate::test] async fn test_with_graceful_shutdown_local_addr() { let router: Router = Router::new(); let addr = "0.0.0.0:0"; let server = serve(TcpListener::bind(addr).await.unwrap(), router.clone()) .with_graceful_shutdown(pending()); let address = server.local_addr().unwrap(); assert_eq!(address.ip(), IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0))); assert_ne!(address.port(), 0); } #[tokio::test(start_paused = true)] async fn test_with_graceful_shutdown_request_header_timeout() { for (timeout, req) in [ // Idle connections (between requests) are closed immediately // when a graceful shutdown is triggered. (0, ""), // idle before request sent (0, "GET / HTTP/1.1\r\n\r\n"), // idle after complete exchange // hyper times stalled request lines/headers out after 30 sec, // after which the graceful shutdown can be completed. (30, "GET / HT"), // stall during request line (30, "GET / HTTP/1.0\r\nAccept: "), // stall during request headers ] { let (mut client, server) = io::duplex(1024); client.write_all(req.as_bytes()).await.unwrap(); let server_task = async { serve(ReadyListener(Some(server)), Router::new()) .with_graceful_shutdown(tokio::time::sleep(Duration::from_secs(1))) .await; }; tokio::time::timeout(Duration::from_secs(timeout + 2), server_task) .await .expect("server_task didn't exit in time"); } } #[tokio::test(start_paused = true)] async fn test_hyper_header_read_timeout_is_enabled() { let header_read_timeout_default = 30; for req in [ "GET / HT", // stall during request line "GET / HTTP/1.0\r\nAccept: ", // stall during request headers ] { let (mut client, server) = io::duplex(1024); client.write_all(req.as_bytes()).await.unwrap(); let server_task = async { serve(ReadyListener(Some(server)), Router::new()).await; }; let wait_for_server_to_close_conn = async { tokio::time::timeout( Duration::from_secs(header_read_timeout_default + 1), client.read_to_end(&mut Vec::new()), ) .await .expect("timeout: server didn't close connection in time") .expect("read_to_end"); }; tokio::select! { _ = server_task => unreachable!(), _ = wait_for_server_to_close_conn => (), }; } } #[test] fn into_future_outside_tokio() { let router: Router = Router::new(); let addr = "0.0.0.0:0"; let rt = tokio::runtime::Builder::new_multi_thread() .enable_all() .build() .unwrap(); let listener = rt.block_on(tokio::net::TcpListener::bind(addr)).unwrap(); // Call Serve::into_future outside of a tokio context. This used to panic. _ = serve(listener, router).into_future(); } #[crate::test] async fn serving_on_custom_io_type() { let (client, server) = io::duplex(1024); let listener = ReadyListener(Some(server)); let app = Router::new().route("/", get(|| async { "Hello, World!" })); tokio::spawn(serve(listener, app).into_future()); let stream = TokioIo::new(client); let (mut sender, conn) = hyper::client::conn::http1::handshake(stream).await.unwrap(); tokio::spawn(conn); let request = Request::builder().body(Body::empty()).unwrap(); let response = sender.send_request(request).await.unwrap(); assert_eq!(response.status(), StatusCode::OK); let body = Body::new(response.into_body()); let body = to_bytes(body, usize::MAX).await.unwrap(); let body = String::from_utf8(body.to_vec()).unwrap(); assert_eq!(body, "Hello, World!"); } #[crate::test] async fn serving_with_custom_body_type() { struct CustomBody; impl http_body::Body for CustomBody { type Data = bytes::Bytes; type Error = std::convert::Infallible; fn poll_frame( self: std::pin::Pin<&mut Self>, _cx: &mut std::task::Context<'_>, ) -> std::task::Poll<Option<Result<http_body::Frame<Self::Data>, Self::Error>>> { #![allow(clippy::unreachable)] // The implementation is not used, we just need to provide one. unreachable!(); } } let app = ServiceBuilder::new() .layer_fn(|_| tower::service_fn(|_| std::future::ready(Ok(Response::new(CustomBody))))) .service(Router::<()>::new().route("/hello", get(|| async {}))); let addr = "0.0.0.0:0"; _ = serve( TcpListener::bind(addr).await.unwrap(), app.into_make_service(), ); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum/src/response/redirect.rs
axum/src/response/redirect.rs
use axum_core::response::{IntoResponse, Response}; use http::{header::LOCATION, HeaderValue, StatusCode}; /// Response that redirects the request to another location. /// /// # Example /// /// ```rust /// use axum::{ /// routing::get, /// response::Redirect, /// Router, /// }; /// /// let app = Router::new() /// .route("/old", get(|| async { Redirect::permanent("/new") })) /// .route("/new", get(|| async { "Hello!" })); /// # let _: Router = app; /// ``` #[must_use = "needs to be returned from a handler or otherwise turned into a Response to be useful"] #[derive(Debug, Clone)] pub struct Redirect { status_code: StatusCode, location: String, } impl Redirect { /// Create a new [`Redirect`] that uses a [`303 See Other`][mdn] status code. /// /// This redirect instructs the client to change the method to GET for the subsequent request /// to the given `uri`, which is useful after successful form submission, file upload or when /// you generally don't want the redirected-to page to observe the original request method and /// body (if non-empty). If you want to preserve the request method and body, /// [`Redirect::temporary`] should be used instead. /// /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/303 pub fn to(uri: &str) -> Self { Self::with_status_code(StatusCode::SEE_OTHER, uri) } /// Create a new [`Redirect`] that uses a [`307 Temporary Redirect`][mdn] status code. /// /// This has the same behavior as [`Redirect::to`], except it will preserve the original HTTP /// method and body. /// /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/307 pub fn temporary(uri: &str) -> Self { Self::with_status_code(StatusCode::TEMPORARY_REDIRECT, uri) } /// Create a new [`Redirect`] that uses a [`308 Permanent Redirect`][mdn] status code. /// /// [mdn]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/308 pub fn permanent(uri: &str) -> Self { Self::with_status_code(StatusCode::PERMANENT_REDIRECT, uri) } /// Returns the HTTP status code of the `Redirect`. #[must_use] pub fn status_code(&self) -> StatusCode { self.status_code } /// Returns the `Redirect`'s URI. #[must_use] pub fn location(&self) -> &str { &self.location } // This is intentionally not public since other kinds of redirects might not // use the `Location` header, namely `304 Not Modified`. // // We're open to adding more constructors upon request, if they make sense :) fn with_status_code(status_code: StatusCode, uri: &str) -> Self { assert!( status_code.is_redirection(), "not a redirection status code" ); Self { status_code, location: uri.to_owned(), } } } impl IntoResponse for Redirect { fn into_response(self) -> Response { match HeaderValue::try_from(self.location) { Ok(location) => (self.status_code, [(LOCATION, location)]).into_response(), Err(error) => (StatusCode::INTERNAL_SERVER_ERROR, error.to_string()).into_response(), } } } #[cfg(test)] mod tests { use super::Redirect; use axum_core::response::IntoResponse; use http::StatusCode; const EXAMPLE_URL: &str = "https://example.com"; // Tests to make sure Redirect has the correct status codes // based on the way it was constructed. #[test] fn correct_status() { assert_eq!( StatusCode::SEE_OTHER, Redirect::to(EXAMPLE_URL).status_code() ); assert_eq!( StatusCode::TEMPORARY_REDIRECT, Redirect::temporary(EXAMPLE_URL).status_code() ); assert_eq!( StatusCode::PERMANENT_REDIRECT, Redirect::permanent(EXAMPLE_URL).status_code() ); } #[test] fn correct_location() { assert_eq!(EXAMPLE_URL, Redirect::permanent(EXAMPLE_URL).location()); assert_eq!("/redirect", Redirect::permanent("/redirect").location()) } #[test] fn test_internal_error() { let response = Redirect::permanent("Axum is awesome, \n but newlines aren't allowed :(") .into_response(); assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum/src/response/mod.rs
axum/src/response/mod.rs
#![doc = include_str!("../docs/response.md")] use http::{header, HeaderValue, StatusCode}; mod redirect; pub mod sse; #[doc(no_inline)] #[cfg(feature = "json")] pub use crate::Json; #[cfg(feature = "form")] #[doc(no_inline)] pub use crate::form::Form; #[doc(no_inline)] pub use crate::Extension; #[doc(inline)] pub use axum_core::response::{ AppendHeaders, ErrorResponse, IntoResponse, IntoResponseParts, Response, ResponseParts, Result, }; #[doc(inline)] pub use self::redirect::Redirect; #[doc(inline)] pub use sse::Sse; /// An HTML response. /// /// Will automatically get `Content-Type: text/html`. #[derive(Clone, Copy, Debug)] #[must_use] pub struct Html<T>(pub T); impl<T> IntoResponse for Html<T> where T: IntoResponse, { fn into_response(self) -> Response { ( [( header::CONTENT_TYPE, HeaderValue::from_static(mime::TEXT_HTML_UTF_8.as_ref()), )], self.0, ) .into_response() } } impl<T> From<T> for Html<T> { fn from(inner: T) -> Self { Self(inner) } } /// An empty response with 204 No Content status. /// /// Due to historical and implementation reasons, the `IntoResponse` implementation of `()` /// (unit type) returns an empty response with 200 [`StatusCode::OK`] status. /// If you specifically want a 204 [`StatusCode::NO_CONTENT`] status, you can use either `StatusCode` type /// directly, or this shortcut struct for self-documentation. /// /// ``` /// use axum::{extract::Path, response::NoContent}; /// /// async fn delete_user(Path(user): Path<String>) -> Result<NoContent, String> { /// // ...access database... /// # drop(user); /// Ok(NoContent) /// } /// ``` #[derive(Debug, Clone, Copy)] pub struct NoContent; impl IntoResponse for NoContent { fn into_response(self) -> Response { StatusCode::NO_CONTENT.into_response() } } #[cfg(test)] mod tests { use crate::extract::Extension; use crate::{routing::get, Router}; use axum_core::response::IntoResponse; use http::HeaderMap; use http::{StatusCode, Uri}; // just needs to compile #[allow(dead_code)] fn impl_trait_result_works() { async fn impl_trait_ok() -> Result<impl IntoResponse, ()> { Ok(()) } async fn impl_trait_err() -> Result<(), impl IntoResponse> { Err(()) } async fn impl_trait_both(uri: Uri) -> Result<impl IntoResponse, impl IntoResponse> { if uri.path() == "/" { Ok(()) } else { Err(()) } } async fn impl_trait(uri: Uri) -> impl IntoResponse { if uri.path() == "/" { Ok(()) } else { Err(()) } } _ = Router::<()>::new() .route("/", get(impl_trait_ok)) .route("/", get(impl_trait_err)) .route("/", get(impl_trait_both)) .route("/", get(impl_trait)); } // just needs to compile #[allow(dead_code)] fn tuple_responses() { async fn status() -> impl IntoResponse { StatusCode::OK } async fn status_headermap() -> impl IntoResponse { (StatusCode::OK, HeaderMap::new()) } async fn status_header_array() -> impl IntoResponse { (StatusCode::OK, [("content-type", "text/plain")]) } async fn status_headermap_body() -> impl IntoResponse { (StatusCode::OK, HeaderMap::new(), String::new()) } async fn status_header_array_body() -> impl IntoResponse { ( StatusCode::OK, [("content-type", "text/plain")], String::new(), ) } async fn status_headermap_impl_into_response() -> impl IntoResponse { (StatusCode::OK, HeaderMap::new(), impl_into_response()) } async fn status_header_array_impl_into_response() -> impl IntoResponse { ( StatusCode::OK, [("content-type", "text/plain")], impl_into_response(), ) } fn impl_into_response() -> impl IntoResponse {} async fn status_header_array_extension_body() -> impl IntoResponse { ( StatusCode::OK, [("content-type", "text/plain")], Extension(1), String::new(), ) } async fn status_header_array_extension_mixed_body() -> impl IntoResponse { ( StatusCode::OK, [("content-type", "text/plain")], Extension(1), HeaderMap::new(), String::new(), ) } // async fn headermap() -> impl IntoResponse { HeaderMap::new() } async fn header_array() -> impl IntoResponse { [("content-type", "text/plain")] } async fn headermap_body() -> impl IntoResponse { (HeaderMap::new(), String::new()) } async fn header_array_body() -> impl IntoResponse { ([("content-type", "text/plain")], String::new()) } async fn headermap_impl_into_response() -> impl IntoResponse { (HeaderMap::new(), impl_into_response()) } async fn header_array_impl_into_response() -> impl IntoResponse { ([("content-type", "text/plain")], impl_into_response()) } async fn header_array_extension_body() -> impl IntoResponse { ( [("content-type", "text/plain")], Extension(1), String::new(), ) } async fn header_array_extension_mixed_body() -> impl IntoResponse { ( [("content-type", "text/plain")], Extension(1), HeaderMap::new(), String::new(), ) } _ = Router::<()>::new() .route("/", get(status)) .route("/", get(status_headermap)) .route("/", get(status_header_array)) .route("/", get(status_headermap_body)) .route("/", get(status_header_array_body)) .route("/", get(status_headermap_impl_into_response)) .route("/", get(status_header_array_impl_into_response)) .route("/", get(status_header_array_extension_body)) .route("/", get(status_header_array_extension_mixed_body)) .route("/", get(headermap)) .route("/", get(header_array)) .route("/", get(headermap_body)) .route("/", get(header_array_body)) .route("/", get(headermap_impl_into_response)) .route("/", get(header_array_impl_into_response)) .route("/", get(header_array_extension_body)) .route("/", get(header_array_extension_mixed_body)); } #[test] fn no_content() { assert_eq!( super::NoContent.into_response().status(), StatusCode::NO_CONTENT, ) } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum/src/response/sse.rs
axum/src/response/sse.rs
//! Server-Sent Events (SSE) responses. //! //! # Example //! //! ``` //! use axum::{ //! Router, //! routing::get, //! response::sse::{Event, KeepAlive, Sse}, //! }; //! use std::{time::Duration, convert::Infallible}; //! use tokio_stream::StreamExt as _ ; //! use futures_util::stream::{self, Stream}; //! //! let app = Router::new().route("/sse", get(sse_handler)); //! //! async fn sse_handler() -> Sse<impl Stream<Item = Result<Event, Infallible>>> { //! // A `Stream` that repeats an event every second //! let stream = stream::repeat_with(|| Event::default().data("hi!")) //! .map(Ok) //! .throttle(Duration::from_secs(1)); //! //! Sse::new(stream).keep_alive(KeepAlive::default()) //! } //! # let _: Router = app; //! ``` use crate::{ body::{Bytes, HttpBody}, BoxError, }; use axum_core::{ body::Body, response::{IntoResponse, Response}, }; use bytes::{BufMut, BytesMut}; use futures_core::Stream; use futures_util::stream::TryStream; use http_body::Frame; use pin_project_lite::pin_project; use std::{ fmt::{self, Write as _}, io::Write as _, mem, pin::Pin, task::{ready, Context, Poll}, time::Duration, }; use sync_wrapper::SyncWrapper; /// An SSE response #[derive(Clone)] #[must_use] pub struct Sse<S> { stream: S, } impl<S> Sse<S> { /// Create a new [`Sse`] response that will respond with the given stream of /// [`Event`]s. /// /// See the [module docs](self) for more details. pub fn new(stream: S) -> Self where S: TryStream<Ok = Event> + Send + 'static, S::Error: Into<BoxError>, { Self { stream } } /// Configure the interval between keep-alive messages. /// /// Defaults to no keep-alive messages. #[cfg(feature = "tokio")] pub fn keep_alive(self, keep_alive: KeepAlive) -> Sse<KeepAliveStream<S>> { Sse { stream: KeepAliveStream::new(keep_alive, self.stream), } } } impl<S> fmt::Debug for Sse<S> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Sse") .field("stream", &format_args!("{}", std::any::type_name::<S>())) .finish() } } impl<S, E> IntoResponse for Sse<S> where S: Stream<Item = Result<Event, E>> + Send + 'static, E: Into<BoxError>, { fn into_response(self) -> Response { ( [ (http::header::CONTENT_TYPE, mime::TEXT_EVENT_STREAM.as_ref()), (http::header::CACHE_CONTROL, "no-cache"), ], Body::new(SseBody { event_stream: SyncWrapper::new(self.stream), }), ) .into_response() } } pin_project! { struct SseBody<S> { #[pin] event_stream: SyncWrapper<S>, } } impl<S, E> HttpBody for SseBody<S> where S: Stream<Item = Result<Event, E>>, { type Data = Bytes; type Error = E; fn poll_frame( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> { let this = self.project(); match ready!(this.event_stream.get_pin_mut().poll_next(cx)) { Some(Ok(event)) => Poll::Ready(Some(Ok(Frame::data(event.finalize())))), Some(Err(error)) => Poll::Ready(Some(Err(error))), None => Poll::Ready(None), } } } /// The state of an event's buffer. /// /// This type allows creating events in a `const` context /// by using a finalized buffer. /// /// While the buffer is active, more bytes can be written to it. /// Once finalized, it's immutable and cheap to clone. /// The buffer is active during the event building, but eventually /// becomes finalized to send http body frames as [`Bytes`]. #[derive(Debug, Clone)] enum Buffer { Active(BytesMut), Finalized(Bytes), } impl Buffer { /// Returns a mutable reference to the internal buffer. /// /// If the buffer was finalized, this method creates /// a new active buffer with the previous contents. fn as_mut(&mut self) -> &mut BytesMut { match self { Self::Active(bytes_mut) => bytes_mut, Self::Finalized(bytes) => { *self = Self::Active(BytesMut::from(mem::take(bytes))); match self { Self::Active(bytes_mut) => bytes_mut, Self::Finalized(_) => unreachable!(), } } } } } /// Server-sent event #[derive(Debug, Clone)] #[must_use] pub struct Event { buffer: Buffer, flags: EventFlags, } /// Expose [`Event`] as a [`std::fmt::Write`] /// such that any form of data can be written as data safely. /// /// This also ensures that newline characters `\r` and `\n` /// correctly trigger a split with a new `data: ` prefix. /// /// # Panics /// /// Panics if any `data` has already been written prior to the first write /// of this [`EventDataWriter`] instance. #[derive(Debug)] #[must_use] pub struct EventDataWriter { event: Event, // Indicates if _this_ EventDataWriter has written data, // this does not say anything about whether or not `event` contains // data or not. data_written: bool, } impl Event { /// Default keep-alive event pub const DEFAULT_KEEP_ALIVE: Self = Self::finalized(Bytes::from_static(b":\n\n")); const fn finalized(bytes: Bytes) -> Self { Self { buffer: Buffer::Finalized(bytes), flags: EventFlags::from_bits(0), } } /// Use this [`Event`] as a [`EventDataWriter`] to write custom data. /// /// - [`Self::data`] can be used as a shortcut to write `str` data /// - [`Self::json_data`] can be used as a shortcut to write `json` data /// /// Turn it into an [`Event`] again using [`EventDataWriter::into_event`]. pub fn into_data_writer(self) -> EventDataWriter { EventDataWriter { event: self, data_written: false, } } /// Set the event's data data field(s) (`data: <content>`) /// /// Newlines in `data` will automatically be broken across `data: ` fields. /// /// This corresponds to [`MessageEvent`'s data field]. /// /// Note that events with an empty data field will be ignored by the browser. /// /// # Panics /// /// Panics if any `data` has already been written before. /// /// [`MessageEvent`'s data field]: https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent/data pub fn data<T>(self, data: T) -> Self where T: AsRef<str>, { let mut writer = self.into_data_writer(); let _ = writer.write_str(data.as_ref()); writer.into_event() } /// Set the event's data field to a value serialized as unformatted JSON (`data: <content>`). /// /// This corresponds to [`MessageEvent`'s data field]. /// /// # Panics /// /// Panics if any `data` has already been written before. /// /// [`MessageEvent`'s data field]: https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent/data #[cfg(feature = "json")] pub fn json_data<T>(self, data: T) -> Result<Self, axum_core::Error> where T: serde_core::Serialize, { struct JsonWriter<'a>(&'a mut EventDataWriter); impl std::io::Write for JsonWriter<'_> { #[inline] fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> { Ok(self.0.write_buf(buf)) } fn flush(&mut self) -> std::io::Result<()> { Ok(()) } } let mut writer = self.into_data_writer(); let json_writer = JsonWriter(&mut writer); serde_json::to_writer(json_writer, &data).map_err(axum_core::Error::new)?; Ok(writer.into_event()) } /// Set the event's comment field (`:<comment-text>`). /// /// This field will be ignored by most SSE clients. /// /// Unlike other functions, this function can be called multiple times to add many comments. /// /// # Panics /// /// Panics if `comment` contains any newlines or carriage returns, as they are not allowed in /// comments. pub fn comment<T>(mut self, comment: T) -> Self where T: AsRef<str>, { self.field("", comment.as_ref()); self } /// Set the event's name field (`event:<event-name>`). /// /// This corresponds to the `type` parameter given when calling `addEventListener` on an /// [`EventSource`]. For example, `.event("update")` should correspond to /// `.addEventListener("update", ...)`. If no event type is given, browsers will fire a /// [`message` event] instead. /// /// [`EventSource`]: https://developer.mozilla.org/en-US/docs/Web/API/EventSource /// [`message` event]: https://developer.mozilla.org/en-US/docs/Web/API/EventSource/message_event /// /// # Panics /// /// - Panics if `event` contains any newlines or carriage returns. /// - Panics if this function has already been called on this event. pub fn event<T>(mut self, event: T) -> Self where T: AsRef<str>, { if self.flags.contains(EventFlags::HAS_EVENT) { panic!("Called `Event::event` multiple times"); } self.flags.insert(EventFlags::HAS_EVENT); self.field("event", event.as_ref()); self } /// Set the event's retry timeout field (`retry: <timeout>`). /// /// This sets how long clients will wait before reconnecting if they are disconnected from the /// SSE endpoint. Note that this is just a hint: clients are free to wait for longer if they /// wish, such as if they implement exponential backoff. /// /// # Panics /// /// Panics if this function has already been called on this event. pub fn retry(mut self, duration: Duration) -> Self { if self.flags.contains(EventFlags::HAS_RETRY) { panic!("Called `Event::retry` multiple times"); } self.flags.insert(EventFlags::HAS_RETRY); let buffer = self.buffer.as_mut(); buffer.extend_from_slice(b"retry: "); let secs = duration.as_secs(); let millis = duration.subsec_millis(); if secs > 0 { // format seconds buffer.extend_from_slice(itoa::Buffer::new().format(secs).as_bytes()); // pad milliseconds if millis < 10 { buffer.extend_from_slice(b"00"); } else if millis < 100 { buffer.extend_from_slice(b"0"); } } // format milliseconds buffer.extend_from_slice(itoa::Buffer::new().format(millis).as_bytes()); buffer.put_u8(b'\n'); self } /// Set the event's identifier field (`id:<identifier>`). /// /// This corresponds to [`MessageEvent`'s `lastEventId` field]. If no ID is in the event itself, /// the browser will set that field to the last known message ID, starting with the empty /// string. /// /// [`MessageEvent`'s `lastEventId` field]: https://developer.mozilla.org/en-US/docs/Web/API/MessageEvent/lastEventId /// /// # Panics /// /// - Panics if `id` contains any newlines, carriage returns or null characters. /// - Panics if this function has already been called on this event. pub fn id<T>(mut self, id: T) -> Self where T: AsRef<str>, { if self.flags.contains(EventFlags::HAS_ID) { panic!("Called `Event::id` multiple times"); } self.flags.insert(EventFlags::HAS_ID); let id = id.as_ref().as_bytes(); assert_eq!( memchr::memchr(b'\0', id), None, "Event ID cannot contain null characters", ); self.field("id", id); self } fn field(&mut self, name: &str, value: impl AsRef<[u8]>) { let value = value.as_ref(); assert_eq!( memchr::memchr2(b'\r', b'\n', value), None, "SSE field value cannot contain newlines or carriage returns", ); let buffer = self.buffer.as_mut(); buffer.extend_from_slice(name.as_bytes()); buffer.put_u8(b':'); buffer.put_u8(b' '); buffer.extend_from_slice(value); buffer.put_u8(b'\n'); } fn finalize(self) -> Bytes { match self.buffer { Buffer::Finalized(bytes) => bytes, Buffer::Active(mut bytes_mut) => { bytes_mut.put_u8(b'\n'); bytes_mut.freeze() } } } } impl EventDataWriter { /// Consume the [`EventDataWriter`] and return the [`Event`] once again. /// /// In case any data was written by this instance /// it will also write the trailing `\n` character. pub fn into_event(self) -> Event { let mut event = self.event; if self.data_written { let _ = event.buffer.as_mut().write_char('\n'); } event } } impl EventDataWriter { // Assumption: underlying writer never returns an error: // <https://docs.rs/bytes/latest/src/bytes/buf/writer.rs.html#79-82> fn write_buf(&mut self, buf: &[u8]) -> usize { if buf.is_empty() { return 0; } let buffer = self.event.buffer.as_mut(); if !std::mem::replace(&mut self.data_written, true) { if self.event.flags.contains(EventFlags::HAS_DATA) { panic!("Called `Event::data*` multiple times"); } let _ = buffer.write_str("data: "); self.event.flags.insert(EventFlags::HAS_DATA); } let mut writer = buffer.writer(); let mut last_split = 0; for delimiter in memchr::memchr2_iter(b'\n', b'\r', buf) { let _ = writer.write_all(&buf[last_split..=delimiter]); let _ = writer.write_all(b"data: "); last_split = delimiter + 1; } let _ = writer.write_all(&buf[last_split..]); buf.len() } } impl fmt::Write for EventDataWriter { fn write_str(&mut self, s: &str) -> fmt::Result { let _ = self.write_buf(s.as_bytes()); Ok(()) } } impl Default for Event { fn default() -> Self { Self { buffer: Buffer::Active(BytesMut::new()), flags: EventFlags::from_bits(0), } } } #[derive(Debug, Copy, Clone, PartialEq)] struct EventFlags(u8); impl EventFlags { const HAS_DATA: Self = Self::from_bits(0b0001); const HAS_EVENT: Self = Self::from_bits(0b0010); const HAS_RETRY: Self = Self::from_bits(0b0100); const HAS_ID: Self = Self::from_bits(0b1000); const fn bits(self) -> u8 { self.0 } const fn from_bits(bits: u8) -> Self { Self(bits) } const fn contains(self, other: Self) -> bool { self.bits() & other.bits() == other.bits() } fn insert(&mut self, other: Self) { *self = Self::from_bits(self.bits() | other.bits()); } } /// Configure the interval between keep-alive messages, the content /// of each message, and the associated stream. #[derive(Debug, Clone)] #[must_use] pub struct KeepAlive { event: Event, max_interval: Duration, } impl KeepAlive { /// Create a new `KeepAlive`. pub fn new() -> Self { Self { event: Event::DEFAULT_KEEP_ALIVE, max_interval: Duration::from_secs(15), } } /// Customize the interval between keep-alive messages. /// /// Default is 15 seconds. pub fn interval(mut self, time: Duration) -> Self { self.max_interval = time; self } /// Customize the text of the keep-alive message. /// /// Default is an empty comment. /// /// # Panics /// /// Panics if `text` contains any newline or carriage returns, as they are not allowed in SSE /// comments. pub fn text<I>(self, text: I) -> Self where I: AsRef<str>, { self.event(Event::default().comment(text)) } /// Customize the event of the keep-alive message. /// /// Default is an empty comment. /// /// # Panics /// /// Panics if `event` contains any newline or carriage returns, as they are not allowed in SSE /// comments. pub fn event(mut self, event: Event) -> Self { self.event = Event::finalized(event.finalize()); self } } impl Default for KeepAlive { fn default() -> Self { Self::new() } } #[cfg(feature = "tokio")] pin_project! { /// A wrapper around a stream that produces keep-alive events #[derive(Debug)] pub struct KeepAliveStream<S> { #[pin] alive_timer: tokio::time::Sleep, #[pin] inner: S, keep_alive: KeepAlive, } } #[cfg(feature = "tokio")] impl<S> KeepAliveStream<S> { fn new(keep_alive: KeepAlive, inner: S) -> Self { Self { alive_timer: tokio::time::sleep(keep_alive.max_interval), inner, keep_alive, } } fn reset(self: Pin<&mut Self>) { let this = self.project(); this.alive_timer .reset(tokio::time::Instant::now() + this.keep_alive.max_interval); } } #[cfg(feature = "tokio")] impl<S, E> Stream for KeepAliveStream<S> where S: Stream<Item = Result<Event, E>>, { type Item = Result<Event, E>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { use std::future::Future; let mut this = self.as_mut().project(); match this.inner.as_mut().poll_next(cx) { Poll::Ready(Some(Ok(event))) => { self.reset(); Poll::Ready(Some(Ok(event))) } Poll::Ready(Some(Err(error))) => Poll::Ready(Some(Err(error))), Poll::Ready(None) => Poll::Ready(None), Poll::Pending => { ready!(this.alive_timer.poll(cx)); let event = this.keep_alive.event.clone(); self.reset(); Poll::Ready(Some(Ok(event))) } } } } #[cfg(test)] mod tests { use super::*; use crate::{routing::get, test_helpers::*, Router}; use futures_util::stream; use serde_json::value::RawValue; use std::{collections::HashMap, convert::Infallible}; use tokio_stream::StreamExt as _; #[test] fn leading_space_is_not_stripped() { let no_leading_space = Event::default().data("\tfoobar"); assert_eq!(&*no_leading_space.finalize(), b"data: \tfoobar\n\n"); let leading_space = Event::default().data(" foobar"); assert_eq!(&*leading_space.finalize(), b"data: foobar\n\n"); } #[test] fn write_data_writer_str() { // also confirm that nop writers do nothing :) let mut writer = Event::default() .into_data_writer() .into_event() .into_data_writer(); writer.write_str("").unwrap(); let mut writer = writer.into_event().into_data_writer(); writer.write_str("").unwrap(); writer.write_str("moon ").unwrap(); writer.write_str("star\nsun").unwrap(); writer.write_str("").unwrap(); writer.write_str("set").unwrap(); writer.write_str("").unwrap(); writer.write_str(" bye\r").unwrap(); let event = writer.into_event(); assert_eq!( &*event.finalize(), b"data: moon star\ndata: sunset bye\rdata: \n\n" ); } #[test] fn valid_json_raw_value_chars_handled() { let json_string = "{\r\"foo\": \n\r\r \"bar\\n\"\n}"; let json_raw_value_event = Event::default() .json_data(serde_json::from_str::<&RawValue>(json_string).unwrap()) .unwrap(); assert_eq!( &*json_raw_value_event.finalize(), b"data: {\rdata: \"foo\": \ndata: \rdata: \rdata: \"bar\\n\"\ndata: }\n\n" ); } #[crate::test] async fn basic() { let app = Router::new().route( "/", get(|| async { let stream = stream::iter(vec![ Event::default().data("one").comment("this is a comment"), Event::default() .json_data(serde_json::json!({ "foo": "bar" })) .unwrap(), Event::default() .event("three") .retry(Duration::from_secs(30)) .id("unique-id"), ]) .map(Ok::<_, Infallible>); Sse::new(stream) }), ); let client = TestClient::new(app); let mut stream = client.get("/").await; assert_eq!(stream.headers()["content-type"], "text/event-stream"); assert_eq!(stream.headers()["cache-control"], "no-cache"); let event_fields = parse_event(&stream.chunk_text().await.unwrap()); assert_eq!(event_fields.get("data").unwrap(), "one"); assert_eq!(event_fields.get("comment").unwrap(), "this is a comment"); let event_fields = parse_event(&stream.chunk_text().await.unwrap()); assert_eq!(event_fields.get("data").unwrap(), "{\"foo\":\"bar\"}"); assert!(!event_fields.contains_key("comment")); let event_fields = parse_event(&stream.chunk_text().await.unwrap()); assert_eq!(event_fields.get("event").unwrap(), "three"); assert_eq!(event_fields.get("retry").unwrap(), "30000"); assert_eq!(event_fields.get("id").unwrap(), "unique-id"); assert!(!event_fields.contains_key("comment")); assert!(stream.chunk_text().await.is_none()); } #[tokio::test(start_paused = true)] async fn keep_alive() { const DELAY: Duration = Duration::from_secs(5); let app = Router::new().route( "/", get(|| async { let stream = stream::repeat_with(|| Event::default().data("msg")) .map(Ok::<_, Infallible>) .throttle(DELAY); Sse::new(stream).keep_alive( KeepAlive::new() .interval(Duration::from_secs(1)) .text("keep-alive-text"), ) }), ); let client = TestClient::new(app); let mut stream = client.get("/").await; for _ in 0..5 { // first message should be an event let event_fields = parse_event(&stream.chunk_text().await.unwrap()); assert_eq!(event_fields.get("data").unwrap(), "msg"); // then 4 seconds of keep-alive messages for _ in 0..4 { tokio::time::sleep(Duration::from_secs(1)).await; let event_fields = parse_event(&stream.chunk_text().await.unwrap()); assert_eq!(event_fields.get("comment").unwrap(), "keep-alive-text"); } } } #[tokio::test(start_paused = true)] async fn keep_alive_ends_when_the_stream_ends() { const DELAY: Duration = Duration::from_secs(5); let app = Router::new().route( "/", get(|| async { let stream = stream::repeat_with(|| Event::default().data("msg")) .map(Ok::<_, Infallible>) .throttle(DELAY) .take(2); Sse::new(stream).keep_alive( KeepAlive::new() .interval(Duration::from_secs(1)) .text("keep-alive-text"), ) }), ); let client = TestClient::new(app); let mut stream = client.get("/").await; // first message should be an event let event_fields = parse_event(&stream.chunk_text().await.unwrap()); assert_eq!(event_fields.get("data").unwrap(), "msg"); // then 4 seconds of keep-alive messages for _ in 0..4 { tokio::time::sleep(Duration::from_secs(1)).await; let event_fields = parse_event(&stream.chunk_text().await.unwrap()); assert_eq!(event_fields.get("comment").unwrap(), "keep-alive-text"); } // then the last event let event_fields = parse_event(&stream.chunk_text().await.unwrap()); assert_eq!(event_fields.get("data").unwrap(), "msg"); // then no more events or keep-alive messages assert!(stream.chunk_text().await.is_none()); } fn parse_event(payload: &str) -> HashMap<String, String> { let mut fields = HashMap::new(); let mut lines = payload.lines().peekable(); while let Some(line) = lines.next() { if line.is_empty() { assert!(lines.next().is_none()); break; } let (mut key, value) = line.split_once(':').unwrap(); let value = value.trim(); if key.is_empty() { key = "comment"; } fields.insert(key.to_owned(), value.to_owned()); } fields } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum/tests/panic_location.rs
axum/tests/panic_location.rs
//! Separate test binary, because the panic hook is a global resource use std::{ panic::{catch_unwind, set_hook, take_hook}, path::Path, sync::OnceLock, }; use axum::{routing::get, Router}; #[test] fn routes_with_overlapping_method_routes() { static PANIC_LOCATION_FILE: OnceLock<String> = OnceLock::new(); let default_hook = take_hook(); set_hook(Box::new(|panic_info| { if let Some(location) = panic_info.location() { _ = PANIC_LOCATION_FILE.set(location.file().to_owned()); } })); let result = catch_unwind(|| { async fn handler() {} let _: Router = Router::new() .route("/foo/bar", get(handler)) .route("/foo/bar", get(handler)); }); set_hook(default_hook); let panic_payload = result.unwrap_err(); let panic_msg = panic_payload.downcast_ref::<String>().unwrap(); assert_eq!( panic_msg, "Overlapping method route. Handler for `GET /foo/bar` already exists" ); let file = PANIC_LOCATION_FILE.get().unwrap(); assert_eq!(Path::new(file).file_name().unwrap(), "panic_location.rs"); }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum/benches/benches.rs
axum/benches/benches.rs
#![allow(missing_docs)] use axum::{ extract::State, routing::{get, post}, Extension, Json, Router, }; use serde::{Deserialize, Serialize}; use std::{ future::IntoFuture, io::BufRead, process::{Command, Stdio}, }; fn main() { if on_ci() { install_rewrk(); } else { ensure_rewrk_is_installed(); } benchmark("minimal").run(Router::new); benchmark("basic") .path("/a/b/c") .run(|| Router::new().route("/a/b/c", get(|| async { "Hello, World!" }))); benchmark("basic-merge").path("/a/b/c").run(|| { let inner = Router::new().route("/a/b/c", get(|| async { "Hello, World!" })); Router::new().merge(inner) }); benchmark("basic-nest").path("/a/b/c").run(|| { let c = Router::new().route("/c", get(|| async { "Hello, World!" })); let b = Router::new().nest("/b", c); Router::new().nest("/a", b) }); benchmark("routing").path("/foo/bar/baz").run(|| { let mut app = Router::new(); for a in 0..10 { for b in 0..10 { for c in 0..10 { app = app.route(&format!("/foo-{a}/bar-{b}/baz-{c}"), get(|| async {})); } } } app.route("/foo/bar/baz", get(|| async {})) }); benchmark("receive-json") .method("post") .headers(&[("content-type", "application/json")]) .body(r#"{"n": 123, "s": "hi there", "b": false}"#) .run(|| Router::new().route("/", post(|_: Json<Payload>| async {}))); benchmark("send-json").run(|| { Router::new().route( "/", get(|| async { Json(Payload { n: 123, s: "hi there".to_owned(), b: false, }) }), ) }); let state = AppState { _string: "aaaaaaaaaaaaaaaaaa".to_owned(), _vec: Vec::from([ "aaaaaaaaaaaaaaaaaa".to_owned(), "bbbbbbbbbbbbbbbbbb".to_owned(), "cccccccccccccccccc".to_owned(), ]), }; benchmark("extension").run(|| { Router::new() .route("/", get(|_: Extension<AppState>| async {})) .layer(Extension(state.clone())) }); benchmark("state").run(|| { Router::new() .route("/", get(|_: State<AppState>| async {})) .with_state(state.clone()) }); } #[derive(Clone)] struct AppState { _string: String, _vec: Vec<String>, } #[derive(Deserialize, Serialize)] struct Payload { n: u32, s: String, b: bool, } fn benchmark(name: &'static str) -> BenchmarkBuilder { BenchmarkBuilder { name, path: None, method: None, headers: None, body: None, } } struct BenchmarkBuilder { name: &'static str, path: Option<&'static str>, method: Option<&'static str>, headers: Option<&'static [(&'static str, &'static str)]>, body: Option<&'static str>, } macro_rules! config_method { ($name:ident, $ty:ty) => { fn $name(mut self, $name: $ty) -> Self { self.$name = Some($name); self } }; } impl BenchmarkBuilder { config_method!(path, &'static str); config_method!(method, &'static str); config_method!(headers, &'static [(&'static str, &'static str)]); config_method!(body, &'static str); fn run<F>(self, f: F) where F: FnOnce() -> Router<()>, { // support only running some benchmarks with // ``` // cargo bench -- routing send-json // ``` let args = std::env::args().collect::<Vec<_>>(); if args.len() != 1 { let names = &args[1..args.len() - 1]; if !names.is_empty() && !names.contains(&self.name.to_owned()) { return; } } let app = f(); let rt = tokio::runtime::Builder::new_multi_thread() .enable_all() .build() .unwrap(); let listener = rt .block_on(tokio::net::TcpListener::bind("0.0.0.0:0")) .unwrap(); let addr = listener.local_addr().unwrap(); #[allow(unreachable_code)] // buggy lint, fixed in nightly std::thread::spawn(move || { rt.block_on(axum::serve(listener, app).into_future()); }); let mut cmd = Command::new("rewrk"); cmd.stdout(Stdio::piped()); cmd.arg("--host"); cmd.arg(format!("http://{addr}{}", self.path.unwrap_or(""))); cmd.args(["--connections", "10"]); cmd.args(["--threads", "10"]); if on_ci() { // don't slow down CI by running the benchmarks for too long // but do run them for a bit cmd.args(["--duration", "1s"]); } else { cmd.args(["--duration", "10s"]); } if let Some(method) = self.method { cmd.args(["--method", method]); } for (key, value) in self.headers.into_iter().flatten() { cmd.arg("--header"); cmd.arg(format!("{key}: {value}")); } if let Some(body) = self.body { cmd.args(["--body", body]); } eprintln!("Running {:?} benchmark", self.name); // indent output from `rewrk` so it's easier to read when running multiple benchmarks let mut child = cmd.spawn().unwrap(); let stdout = child.stdout.take().unwrap(); let stdout = std::io::BufReader::new(stdout); for line in stdout.lines() { let line = line.unwrap(); println!(" {line}"); } let status = child.wait().unwrap(); if !status.success() { eprintln!("`rewrk` command failed"); std::process::exit(status.code().unwrap()); } } } fn install_rewrk() { println!("installing rewrk"); let mut cmd = Command::new("cargo"); cmd.args([ "install", "rewrk", "--git", "https://github.com/ChillFish8/rewrk.git", ]); let status = cmd .status() .unwrap_or_else(|_| panic!("failed to install rewrk")); if !status.success() { panic!("failed to install rewrk"); } } fn ensure_rewrk_is_installed() { let mut cmd = Command::new("rewrk"); cmd.arg("--help"); cmd.stdout(Stdio::null()); cmd.stderr(Stdio::null()); cmd.status().unwrap_or_else(|_| { panic!("rewrk is not installed. See https://github.com/lnx-search/rewrk") }); } fn on_ci() -> bool { std::env::var("GITHUB_ACTIONS").is_ok() }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-core/src/lib.rs
axum-core/src/lib.rs
//! Core types and traits for [`axum`]. //! //! Libraries authors that want to provide [`FromRequest`] or [`IntoResponse`] implementations //! should depend on the [`axum-core`] crate, instead of `axum` if possible. //! //! [`FromRequest`]: crate::extract::FromRequest //! [`IntoResponse`]: crate::response::IntoResponse //! [`axum`]: https://crates.io/crates/axum //! [`axum-core`]: http://crates.io/crates/axum-core #![cfg_attr(test, allow(clippy::float_cmp))] #![cfg_attr(not(test), warn(clippy::print_stdout, clippy::dbg_macro))] #[macro_use] pub(crate) mod macros; #[doc(hidden)] // macro helpers pub mod __private { #[cfg(feature = "tracing")] pub use tracing; } mod error; mod ext_traits; pub use self::error::Error; pub mod body; pub mod extract; pub mod response; /// Alias for a type-erased error type. pub type BoxError = Box<dyn std::error::Error + Send + Sync>; pub use self::ext_traits::{request::RequestExt, request_parts::RequestPartsExt}; #[cfg(test)] use axum_macros::__private_axum_test as test;
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-core/src/error.rs
axum-core/src/error.rs
use crate::BoxError; use std::{error::Error as StdError, fmt}; /// Errors that can happen when using axum. #[derive(Debug)] pub struct Error { inner: BoxError, } impl Error { /// Create a new `Error` from a boxable error. pub fn new(error: impl Into<BoxError>) -> Self { Self { inner: error.into(), } } /// Convert an `Error` back into the underlying boxed trait object. #[must_use] pub fn into_inner(self) -> BoxError { self.inner } } impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.inner.fmt(f) } } impl StdError for Error { fn source(&self) -> Option<&(dyn StdError + 'static)> { Some(&*self.inner) } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-core/src/macros.rs
axum-core/src/macros.rs
/// Private API. #[cfg(feature = "tracing")] #[doc(hidden)] #[macro_export] macro_rules! __log_rejection { ( rejection_type = $ty:ident, body_text = $body_text:expr, status = $status:expr, ) => { { $crate::__private::tracing::event!( target: "axum::rejection", $crate::__private::tracing::Level::TRACE, status = $status.as_u16(), body = $body_text, rejection_type = ::std::any::type_name::<$ty>(), "rejecting request", ); } }; } #[cfg(not(feature = "tracing"))] #[doc(hidden)] #[macro_export] macro_rules! __log_rejection { ( rejection_type = $ty:ident, body_text = $body_text:expr, status = $status:expr, ) => {}; } /// Private API. #[doc(hidden)] #[macro_export] macro_rules! __define_rejection { ( #[status = $status:ident] #[body = $body:literal] $(#[$m:meta])* pub struct $name:ident; ) => { $(#[$m])* #[derive(Debug)] #[non_exhaustive] pub struct $name; impl $name { /// Get the response body text used for this rejection. pub fn body_text(&self) -> String { self.to_string() } /// Get the status code used for this rejection. pub fn status(&self) -> http::StatusCode { http::StatusCode::$status } } impl $crate::response::IntoResponse for $name { fn into_response(self) -> $crate::response::Response { let status = self.status(); $crate::__log_rejection!( rejection_type = $name, body_text = $body, status = status, ); (status, $body).into_response() } } impl std::fmt::Display for $name { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", $body) } } impl std::error::Error for $name {} impl Default for $name { fn default() -> Self { Self } } }; ( #[status = $status:ident] #[body = $body:literal] $(#[$m:meta])* pub struct $name:ident (Error); ) => { $(#[$m])* #[derive(Debug)] pub struct $name(pub(crate) $crate::Error); impl $name { pub(crate) fn from_err<E>(err: E) -> Self where E: Into<$crate::BoxError>, { Self($crate::Error::new(err)) } /// Get the response body text used for this rejection. #[must_use] pub fn body_text(&self) -> String { self.to_string() } /// Get the status code used for this rejection. #[must_use] pub fn status(&self) -> http::StatusCode { http::StatusCode::$status } } impl $crate::response::IntoResponse for $name { fn into_response(self) -> $crate::response::Response { let status = self.status(); let body_text = self.body_text(); $crate::__log_rejection!( rejection_type = $name, body_text = body_text, status = status, ); (status, body_text).into_response() } } impl std::fmt::Display for $name { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.write_str($body)?; f.write_str(": ")?; self.0.fmt(f) } } impl std::error::Error for $name { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.0) } } }; } /// Private API. #[doc(hidden)] #[macro_export] macro_rules! __composite_rejection { ( $(#[$m:meta])* pub enum $name:ident { $($variant:ident),+ $(,)? } ) => { $(#[$m])* #[derive(Debug)] #[non_exhaustive] pub enum $name { $( #[allow(missing_docs)] $variant($variant) ),+ } impl $crate::response::IntoResponse for $name { fn into_response(self) -> $crate::response::Response { match self { $( Self::$variant(inner) => inner.into_response(), )+ } } } impl $name { /// Get the response body text used for this rejection. #[must_use] pub fn body_text(&self) -> String { match self { $( Self::$variant(inner) => inner.body_text(), )+ } } /// Get the status code used for this rejection. #[must_use] pub fn status(&self) -> http::StatusCode { match self { $( Self::$variant(inner) => inner.status(), )+ } } } $( impl From<$variant> for $name { fn from(inner: $variant) -> Self { Self::$variant(inner) } } )+ impl std::fmt::Display for $name { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { $( Self::$variant(inner) => write!(f, "{inner}"), )+ } } } impl std::error::Error for $name { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match self { $( Self::$variant(inner) => inner.source(), )+ } } } }; } #[rustfmt::skip] macro_rules! all_the_tuples { ($name:ident) => { $name!([], T1); $name!([T1], T2); $name!([T1, T2], T3); $name!([T1, T2, T3], T4); $name!([T1, T2, T3, T4], T5); $name!([T1, T2, T3, T4, T5], T6); $name!([T1, T2, T3, T4, T5, T6], T7); $name!([T1, T2, T3, T4, T5, T6, T7], T8); $name!([T1, T2, T3, T4, T5, T6, T7, T8], T9); $name!([T1, T2, T3, T4, T5, T6, T7, T8, T9], T10); $name!([T1, T2, T3, T4, T5, T6, T7, T8, T9, T10], T11); $name!([T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11], T12); $name!([T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12], T13); $name!([T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13], T14); $name!([T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14], T15); $name!([T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15], T16); }; } macro_rules! all_the_tuples_no_last_special_case { ($name:ident) => { $name!(T1); $name!(T1, T2); $name!(T1, T2, T3); $name!(T1, T2, T3, T4); $name!(T1, T2, T3, T4, T5); $name!(T1, T2, T3, T4, T5, T6); $name!(T1, T2, T3, T4, T5, T6, T7); $name!(T1, T2, T3, T4, T5, T6, T7, T8); $name!(T1, T2, T3, T4, T5, T6, T7, T8, T9); $name!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10); $name!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11); $name!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12); $name!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13); $name!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14); $name!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15); $name!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16); }; } /// Private API. #[doc(hidden)] #[macro_export] macro_rules! __impl_deref { ($ident:ident) => { impl<T> std::ops::Deref for $ident<T> { type Target = T; #[inline] fn deref(&self) -> &Self::Target { &self.0 } } impl<T> std::ops::DerefMut for $ident<T> { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } }; ($ident:ident: $ty:ty) => { impl std::ops::Deref for $ident { type Target = $ty; #[inline] fn deref(&self) -> &Self::Target { &self.0 } } impl std::ops::DerefMut for $ident { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } }; } #[cfg(test)] mod composite_rejection_tests { use self::defs::*; use crate::Error; use std::error::Error as _; #[allow(dead_code, unreachable_pub)] mod defs { __define_rejection! { #[status = BAD_REQUEST] #[body = "error message 1"] pub struct Inner1; } __define_rejection! { #[status = BAD_REQUEST] #[body = "error message 2"] pub struct Inner2(Error); } __composite_rejection! { pub enum Outer { Inner1, Inner2 } } } /// The implementation of `.source()` on `Outer` should defer straight to the implementation /// on its inner type instead of returning the inner type itself, because the `Display` /// implementation on `Outer` already forwards to the inner type and so it would result in two /// errors in the chain `Display`ing the same thing. #[test] fn source_gives_inner_source() { let rejection = Outer::Inner1(Inner1); assert!(rejection.source().is_none()); let msg = "hello world"; let rejection = Outer::Inner2(Inner2(Error::new(msg))); assert_eq!(rejection.source().unwrap().to_string(), msg); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-core/src/body.rs
axum-core/src/body.rs
//! HTTP body utilities. use crate::{BoxError, Error}; use bytes::Bytes; use futures_core::{Stream, TryStream}; use http_body::{Body as _, Frame}; use http_body_util::BodyExt; use pin_project_lite::pin_project; use std::pin::Pin; use std::task::{ready, Context, Poll}; use sync_wrapper::SyncWrapper; type BoxBody = http_body_util::combinators::UnsyncBoxBody<Bytes, Error>; fn boxed<B>(body: B) -> BoxBody where B: http_body::Body<Data = Bytes> + Send + 'static, B::Error: Into<BoxError>, { try_downcast(body).unwrap_or_else(|body| body.map_err(Error::new).boxed_unsync()) } pub(crate) fn try_downcast<T, K>(k: K) -> Result<T, K> where T: 'static, K: Send + 'static, { let mut k = Some(k); if let Some(k) = <dyn std::any::Any>::downcast_mut::<Option<T>>(&mut k) { Ok(k.take().unwrap()) } else { Err(k.unwrap()) } } /// The body type used in axum requests and responses. #[must_use] #[derive(Debug)] pub struct Body(BoxBody); impl Body { /// Create a new `Body` that wraps another [`http_body::Body`]. pub fn new<B>(body: B) -> Self where B: http_body::Body<Data = Bytes> + Send + 'static, B::Error: Into<BoxError>, { try_downcast(body).unwrap_or_else(|body| Self(boxed(body))) } /// Create an empty body. pub fn empty() -> Self { Self::new(http_body_util::Empty::new()) } /// Create a new `Body` from a [`Stream`]. /// /// [`Stream`]: https://docs.rs/futures-core/latest/futures_core/stream/trait.Stream.html pub fn from_stream<S>(stream: S) -> Self where S: TryStream + Send + 'static, S::Ok: Into<Bytes>, S::Error: Into<BoxError>, { Self::new(StreamBody { stream: SyncWrapper::new(stream), }) } /// Convert the body into a [`Stream`] of data frames. /// /// Non-data frames (such as trailers) will be discarded. Use [`http_body_util::BodyStream`] if /// you need a [`Stream`] of all frame types. /// /// [`http_body_util::BodyStream`]: https://docs.rs/http-body-util/latest/http_body_util/struct.BodyStream.html pub fn into_data_stream(self) -> BodyDataStream { BodyDataStream { inner: self } } } impl Default for Body { fn default() -> Self { Self::empty() } } impl From<()> for Body { fn from(_: ()) -> Self { Self::empty() } } macro_rules! body_from_impl { ($ty:ty) => { impl From<$ty> for Body { fn from(buf: $ty) -> Self { Self::new(http_body_util::Full::from(buf)) } } }; } body_from_impl!(&'static [u8]); body_from_impl!(std::borrow::Cow<'static, [u8]>); body_from_impl!(Vec<u8>); 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_frame( mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> { Pin::new(&mut self.0).poll_frame(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() } } /// A stream of data frames. /// /// Created with [`Body::into_data_stream`]. #[must_use] #[derive(Debug)] pub struct BodyDataStream { inner: Body, } impl Stream for BodyDataStream { type Item = Result<Bytes, Error>; #[inline] fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { loop { match ready!(Pin::new(&mut self.inner).poll_frame(cx)?) { Some(frame) => match frame.into_data() { Ok(data) => return Poll::Ready(Some(Ok(data))), Err(_frame) => {} }, None => return Poll::Ready(None), } } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let size_hint = self.inner.size_hint(); let lower = usize::try_from(size_hint.lower()).unwrap_or_default(); let upper = size_hint.upper().and_then(|v| usize::try_from(v).ok()); (lower, upper) } } impl http_body::Body for BodyDataStream { type Data = Bytes; type Error = Error; #[inline] fn poll_frame( mut self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> { Pin::new(&mut self.inner).poll_frame(cx) } #[inline] fn is_end_stream(&self) -> bool { self.inner.is_end_stream() } #[inline] fn size_hint(&self) -> http_body::SizeHint { self.inner.size_hint() } } pin_project! { struct StreamBody<S> { #[pin] stream: SyncWrapper<S>, } } impl<S> http_body::Body for StreamBody<S> where S: TryStream, S::Ok: Into<Bytes>, S::Error: Into<BoxError>, { type Data = Bytes; type Error = Error; fn poll_frame( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> { let stream = self.project().stream.get_pin_mut(); match ready!(stream.try_poll_next(cx)) { Some(Ok(chunk)) => Poll::Ready(Some(Ok(Frame::data(chunk.into())))), Some(Err(err)) => Poll::Ready(Some(Err(Error::new(err)))), None => Poll::Ready(None), } } } #[test] fn test_try_downcast() { assert_eq!(try_downcast::<i32, _>(5_u32), Err(5_u32)); assert_eq!(try_downcast::<i32, _>(5_i32), Ok(5_i32)); }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-core/src/ext_traits/request_parts.rs
axum-core/src/ext_traits/request_parts.rs
use crate::extract::FromRequestParts; use http::request::Parts; use std::future::Future; mod sealed { pub trait Sealed {} impl Sealed for http::request::Parts {} } /// Extension trait that adds additional methods to [`Parts`]. pub trait RequestPartsExt: sealed::Sealed + Sized { /// Apply an extractor to this `Parts`. /// /// This is just a convenience for `E::from_request_parts(parts, &())`. /// /// # Example /// /// ``` /// use axum::{ /// extract::{Query, Path, FromRequestParts}, /// response::{Response, IntoResponse}, /// http::request::Parts, /// RequestPartsExt, /// }; /// use std::collections::HashMap; /// /// struct MyExtractor { /// path_params: HashMap<String, String>, /// query_params: HashMap<String, String>, /// } /// /// impl<S> FromRequestParts<S> for MyExtractor /// where /// S: Send + Sync, /// { /// type Rejection = Response; /// /// async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { /// let path_params = parts /// .extract::<Path<HashMap<String, String>>>() /// .await /// .map(|Path(path_params)| path_params) /// .map_err(|err| err.into_response())?; /// /// let query_params = parts /// .extract::<Query<HashMap<String, String>>>() /// .await /// .map(|Query(params)| params) /// .map_err(|err| err.into_response())?; /// /// Ok(MyExtractor { path_params, query_params }) /// } /// } /// ``` fn extract<E>(&mut self) -> impl Future<Output = Result<E, E::Rejection>> + Send where E: FromRequestParts<()> + 'static; /// Apply an extractor that requires some state to this `Parts`. /// /// This is just a convenience for `E::from_request_parts(parts, state)`. /// /// # Example /// /// ``` /// use axum::{ /// extract::{FromRef, FromRequestParts}, /// response::{Response, IntoResponse}, /// http::request::Parts, /// RequestPartsExt, /// }; /// /// struct MyExtractor { /// requires_state: RequiresState, /// } /// /// impl<S> FromRequestParts<S> for MyExtractor /// where /// String: FromRef<S>, /// S: Send + Sync, /// { /// type Rejection = std::convert::Infallible; /// /// async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { /// let requires_state = parts /// .extract_with_state::<RequiresState, _>(state) /// .await?; /// /// Ok(MyExtractor { requires_state }) /// } /// } /// /// struct RequiresState { /* ... */ } /// /// // some extractor that requires a `String` in the state /// impl<S> FromRequestParts<S> for RequiresState /// where /// String: FromRef<S>, /// S: Send + Sync, /// { /// // ... /// # type Rejection = std::convert::Infallible; /// # async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { /// # unimplemented!() /// # } /// } /// ``` fn extract_with_state<'a, E, S>( &'a mut self, state: &'a S, ) -> impl Future<Output = Result<E, E::Rejection>> + Send + 'a where E: FromRequestParts<S> + 'static, S: Send + Sync; } impl RequestPartsExt for Parts { fn extract<E>(&mut self) -> impl Future<Output = Result<E, E::Rejection>> + Send where E: FromRequestParts<()> + 'static, { self.extract_with_state(&()) } fn extract_with_state<'a, E, S>( &'a mut self, state: &'a S, ) -> impl Future<Output = Result<E, E::Rejection>> + Send + 'a where E: FromRequestParts<S> + 'static, S: Send + Sync, { E::from_request_parts(self, state) } } #[cfg(test)] mod tests { use std::convert::Infallible; use super::*; use crate::{ ext_traits::tests::{RequiresState, State}, extract::FromRef, }; use http::{Method, Request}; #[tokio::test] async fn extract_without_state() { let (mut parts, _) = Request::new(()).into_parts(); let method: Method = parts.extract().await.unwrap(); assert_eq!(method, Method::GET); } #[tokio::test] async fn extract_with_state() { let (mut parts, _) = Request::new(()).into_parts(); let state = "state".to_owned(); let State(extracted_state): State<String> = parts .extract_with_state::<State<String>, String>(&state) .await .unwrap(); assert_eq!(extracted_state, state); } // this stuff just needs to compile #[allow(dead_code)] struct WorksForCustomExtractor { method: Method, from_state: String, } impl<S> FromRequestParts<S> for WorksForCustomExtractor where S: Send + Sync, String: FromRef<S>, { type Rejection = Infallible; async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { let RequiresState(from_state) = parts.extract_with_state(state).await?; let method = parts.extract().await?; Ok(Self { method, from_state }) } } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-core/src/ext_traits/mod.rs
axum-core/src/ext_traits/mod.rs
pub(crate) mod request; pub(crate) mod request_parts; #[cfg(test)] mod tests { use std::convert::Infallible; use crate::extract::{FromRef, FromRequestParts}; use http::request::Parts; #[derive(Debug, Default, Clone, Copy)] pub(crate) struct State<S>(pub(crate) S); impl<OuterState, InnerState> FromRequestParts<OuterState> for State<InnerState> where InnerState: FromRef<OuterState>, OuterState: Send + Sync, { type Rejection = Infallible; async fn from_request_parts( _parts: &mut Parts, state: &OuterState, ) -> Result<Self, Self::Rejection> { let inner_state = InnerState::from_ref(state); Ok(Self(inner_state)) } } // some extractor that requires the state, such as `SignedCookieJar` #[allow(dead_code)] pub(crate) struct RequiresState(pub(crate) String); impl<S> FromRequestParts<S> for RequiresState where S: Send + Sync, String: FromRef<S>, { type Rejection = Infallible; async fn from_request_parts( _parts: &mut Parts, state: &S, ) -> Result<Self, Self::Rejection> { Ok(Self(String::from_ref(state))) } } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-core/src/ext_traits/request.rs
axum-core/src/ext_traits/request.rs
use crate::body::Body; use crate::extract::{DefaultBodyLimitKind, FromRequest, FromRequestParts, Request}; use std::future::Future; mod sealed { pub trait Sealed {} impl Sealed for http::Request<crate::body::Body> {} } /// Extension trait that adds additional methods to [`Request`]. pub trait RequestExt: sealed::Sealed + Sized { /// Apply an extractor to this `Request`. /// /// This is just a convenience for `E::from_request(req, &())`. /// /// Note this consumes the request. Use [`RequestExt::extract_parts`] if you're not extracting /// the body and don't want to consume the request. /// /// # Example /// /// ``` /// use axum::{ /// extract::{Request, FromRequest}, /// body::Body, /// http::{header::CONTENT_TYPE, StatusCode}, /// response::{IntoResponse, Response}, /// Form, Json, RequestExt, /// }; /// /// struct FormOrJson<T>(T); /// /// impl<S, T> FromRequest<S> for FormOrJson<T> /// where /// Json<T>: FromRequest<()>, /// Form<T>: FromRequest<()>, /// T: 'static, /// S: Send + Sync, /// { /// type Rejection = Response; /// /// async fn from_request(req: Request, _state: &S) -> Result<Self, Self::Rejection> { /// let content_type = req /// .headers() /// .get(CONTENT_TYPE) /// .and_then(|value| value.to_str().ok()) /// .ok_or_else(|| StatusCode::BAD_REQUEST.into_response())?; /// /// if content_type.starts_with("application/json") { /// let Json(payload) = req /// .extract::<Json<T>, _>() /// .await /// .map_err(|err| err.into_response())?; /// /// Ok(Self(payload)) /// } else if content_type.starts_with("application/x-www-form-urlencoded") { /// let Form(payload) = req /// .extract::<Form<T>, _>() /// .await /// .map_err(|err| err.into_response())?; /// /// Ok(Self(payload)) /// } else { /// Err(StatusCode::BAD_REQUEST.into_response()) /// } /// } /// } /// ``` fn extract<E, M>(self) -> impl Future<Output = Result<E, E::Rejection>> + Send where E: FromRequest<(), M> + 'static, M: 'static; /// Apply an extractor that requires some state to this `Request`. /// /// This is just a convenience for `E::from_request(req, state)`. /// /// Note this consumes the request. Use [`RequestExt::extract_parts_with_state`] if you're not /// extracting the body and don't want to consume the request. /// /// # Example /// /// ``` /// use axum::{ /// body::Body, /// extract::{Request, FromRef, FromRequest}, /// RequestExt, /// }; /// /// struct MyExtractor { /// requires_state: RequiresState, /// } /// /// impl<S> FromRequest<S> for MyExtractor /// where /// String: FromRef<S>, /// S: Send + Sync, /// { /// type Rejection = std::convert::Infallible; /// /// async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> { /// let requires_state = req.extract_with_state::<RequiresState, _, _>(state).await?; /// /// Ok(Self { requires_state }) /// } /// } /// /// // some extractor that consumes the request body and requires state /// struct RequiresState { /* ... */ } /// /// impl<S> FromRequest<S> for RequiresState /// where /// String: FromRef<S>, /// S: Send + Sync, /// { /// // ... /// # type Rejection = std::convert::Infallible; /// # async fn from_request(req: Request, _state: &S) -> Result<Self, Self::Rejection> { /// # todo!() /// # } /// } /// ``` fn extract_with_state<E, S, M>( self, state: &S, ) -> impl Future<Output = Result<E, E::Rejection>> + Send where E: FromRequest<S, M> + 'static, S: Send + Sync; /// Apply a parts extractor to this `Request`. /// /// This is just a convenience for `E::from_request_parts(parts, state)`. /// /// # Example /// /// ``` /// use axum::{ /// extract::{Path, Request, FromRequest}, /// response::{IntoResponse, Response}, /// body::Body, /// Json, RequestExt, /// }; /// use axum_extra::{ /// TypedHeader, /// headers::{authorization::Bearer, Authorization}, /// }; /// use std::collections::HashMap; /// /// struct MyExtractor<T> { /// path_params: HashMap<String, String>, /// payload: T, /// } /// /// impl<S, T> FromRequest<S> for MyExtractor<T> /// where /// S: Send + Sync, /// Json<T>: FromRequest<()>, /// T: 'static, /// { /// type Rejection = Response; /// /// async fn from_request(mut req: Request, _state: &S) -> Result<Self, Self::Rejection> { /// let path_params = req /// .extract_parts::<Path<_>>() /// .await /// .map(|Path(path_params)| path_params) /// .map_err(|err| err.into_response())?; /// /// let Json(payload) = req /// .extract::<Json<T>, _>() /// .await /// .map_err(|err| err.into_response())?; /// /// Ok(Self { path_params, payload }) /// } /// } /// ``` fn extract_parts<E>(&mut self) -> impl Future<Output = Result<E, E::Rejection>> + Send where E: FromRequestParts<()> + 'static; /// Apply a parts extractor that requires some state to this `Request`. /// /// This is just a convenience for `E::from_request_parts(parts, state)`. /// /// # Example /// /// ``` /// use axum::{ /// extract::{Request, FromRef, FromRequest, FromRequestParts}, /// http::request::Parts, /// response::{IntoResponse, Response}, /// body::Body, /// Json, RequestExt, /// }; /// /// struct MyExtractor<T> { /// requires_state: RequiresState, /// payload: T, /// } /// /// impl<S, T> FromRequest<S> for MyExtractor<T> /// where /// String: FromRef<S>, /// Json<T>: FromRequest<()>, /// T: 'static, /// S: Send + Sync, /// { /// type Rejection = Response; /// /// async fn from_request(mut req: Request, state: &S) -> Result<Self, Self::Rejection> { /// let requires_state = req /// .extract_parts_with_state::<RequiresState, _>(state) /// .await /// .map_err(|err| err.into_response())?; /// /// let Json(payload) = req /// .extract::<Json<T>, _>() /// .await /// .map_err(|err| err.into_response())?; /// /// Ok(Self { /// requires_state, /// payload, /// }) /// } /// } /// /// struct RequiresState {} /// /// impl<S> FromRequestParts<S> for RequiresState /// where /// String: FromRef<S>, /// S: Send + Sync, /// { /// // ... /// # type Rejection = std::convert::Infallible; /// # async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { /// # todo!() /// # } /// } /// ``` fn extract_parts_with_state<'a, E, S>( &'a mut self, state: &'a S, ) -> impl Future<Output = Result<E, E::Rejection>> + Send + 'a where E: FromRequestParts<S> + 'static, S: Send + Sync; /// Apply the [default body limit](crate::extract::DefaultBodyLimit). /// /// If it is disabled, the request is returned as-is. fn with_limited_body(self) -> Request; /// Consumes the request, returning the body wrapped in [`http_body_util::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) -> Body; } impl RequestExt for Request { fn extract<E, M>(self) -> impl Future<Output = Result<E, E::Rejection>> + Send where E: FromRequest<(), M> + 'static, M: 'static, { self.extract_with_state(&()) } fn extract_with_state<E, S, M>( self, state: &S, ) -> impl Future<Output = Result<E, E::Rejection>> + Send where E: FromRequest<S, M> + 'static, S: Send + Sync, { E::from_request(self, state) } fn extract_parts<E>(&mut self) -> impl Future<Output = Result<E, E::Rejection>> + Send where E: FromRequestParts<()> + 'static, { self.extract_parts_with_state(&()) } async fn extract_parts_with_state<'a, E, S>( &'a mut self, state: &'a S, ) -> Result<E, E::Rejection> where E: FromRequestParts<S> + 'static, S: Send + Sync, { let mut req = Request::new(()); *req.version_mut() = self.version(); *req.method_mut() = self.method().clone(); *req.uri_mut() = self.uri().clone(); *req.headers_mut() = std::mem::take(self.headers_mut()); *req.extensions_mut() = std::mem::take(self.extensions_mut()); let (mut parts, ()) = req.into_parts(); let result = E::from_request_parts(&mut parts, state).await; *self.version_mut() = parts.version; *self.method_mut() = parts.method.clone(); *self.uri_mut() = parts.uri.clone(); *self.headers_mut() = std::mem::take(&mut parts.headers); *self.extensions_mut() = std::mem::take(&mut parts.extensions); result } fn with_limited_body(self) -> 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 match self.extensions().get::<DefaultBodyLimitKind>().copied() { Some(DefaultBodyLimitKind::Disable) => self, Some(DefaultBodyLimitKind::Limit(limit)) => { self.map(|b| Body::new(http_body_util::Limited::new(b, limit))) } None => self.map(|b| Body::new(http_body_util::Limited::new(b, DEFAULT_LIMIT))), } } fn into_limited_body(self) -> Body { self.with_limited_body().into_body() } } #[cfg(test)] mod tests { use super::*; use crate::{ ext_traits::tests::{RequiresState, State}, extract::FromRef, }; use http::Method; #[tokio::test] async fn extract_without_state() { let req = Request::new(Body::empty()); let method: Method = req.extract().await.unwrap(); assert_eq!(method, Method::GET); } #[tokio::test] async fn extract_body_without_state() { let req = Request::new(Body::from("foobar")); let body: String = req.extract().await.unwrap(); assert_eq!(body, "foobar"); } #[tokio::test] async fn extract_with_state() { let req = Request::new(Body::empty()); let state = "state".to_owned(); let State(extracted_state): State<String> = req.extract_with_state(&state).await.unwrap(); assert_eq!(extracted_state, state); } #[tokio::test] async fn extract_parts_without_state() { let mut req = Request::builder() .header("x-foo", "foo") .body(Body::empty()) .unwrap(); let method: Method = req.extract_parts().await.unwrap(); assert_eq!(method, Method::GET); assert_eq!(req.headers()["x-foo"], "foo"); } #[tokio::test] async fn extract_parts_with_state() { let mut req = Request::builder() .header("x-foo", "foo") .body(Body::empty()) .unwrap(); let state = "state".to_owned(); let State(extracted_state): State<String> = req.extract_parts_with_state(&state).await.unwrap(); assert_eq!(extracted_state, state); assert_eq!(req.headers()["x-foo"], "foo"); } // this stuff just needs to compile #[allow(dead_code)] struct WorksForCustomExtractor { method: Method, from_state: String, body: String, } impl<S> FromRequest<S> for WorksForCustomExtractor where S: Send + Sync, String: FromRef<S> + FromRequest<()>, { type Rejection = <String as FromRequest<()>>::Rejection; async fn from_request(mut req: Request, state: &S) -> Result<Self, Self::Rejection> { let RequiresState(from_state) = req.extract_parts_with_state(state).await.unwrap(); let method = req.extract_parts().await.unwrap(); let body = req.extract().await?; Ok(Self { method, from_state, body, }) } } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-core/src/extract/default_body_limit.rs
axum-core/src/extract/default_body_limit.rs
use self::private::DefaultBodyLimitService; use http::Request; use tower_layer::Layer; /// Layer for configuring the default request body limit. /// /// For security reasons, [`Bytes`] will, by default, not accept bodies larger than 2MB. This also /// applies to extractors that uses [`Bytes`] internally such as `String`, [`Json`], and [`Form`]. /// /// This middleware provides ways to configure that. /// /// Note that if an extractor consumes the body directly with [`Body::poll_frame`], or similar, the /// default limit is _not_ applied. /// /// # Difference between `DefaultBodyLimit` and [`RequestBodyLimit`] /// /// `DefaultBodyLimit` and [`RequestBodyLimit`] serve similar functions but in different ways. /// /// `DefaultBodyLimit` is local in that it only applies to [`FromRequest`] implementations that /// explicitly apply it (or call another extractor that does). You can apply the limit with /// [`RequestExt::with_limited_body`] or [`RequestExt::into_limited_body`] /// /// [`RequestBodyLimit`] is applied globally to all requests, regardless of which extractors are /// used or how the body is consumed. /// /// # Example /// /// ``` /// use axum::{ /// Router, /// routing::post, /// body::Body, /// extract::{Request, DefaultBodyLimit}, /// }; /// /// let app = Router::new() /// .route("/", post(|request: Request| async {})) /// // change the default limit /// .layer(DefaultBodyLimit::max(1024)); /// # let _: Router = app; /// ``` /// /// In general using `DefaultBodyLimit` is recommended but if you need to use third party /// extractors and want to make sure a limit is also applied there then [`RequestBodyLimit`] should /// be used. /// /// # Different limits for different routes /// /// `DefaultBodyLimit` can also be selectively applied to have different limits for different /// routes: /// /// ``` /// use axum::{ /// Router, /// routing::post, /// body::Body, /// extract::{Request, DefaultBodyLimit}, /// }; /// /// let app = Router::new() /// // this route has a different limit /// .route("/", post(|request: Request| async {}).layer(DefaultBodyLimit::max(1024))) /// // this route still has the default limit /// .route("/foo", post(|request: Request| async {})); /// # let _: Router = app; /// ``` /// /// [`Body::poll_frame`]: http_body::Body::poll_frame /// [`Bytes`]: bytes::Bytes /// [`Json`]: https://docs.rs/axum/0.8/axum/struct.Json.html /// [`Form`]: https://docs.rs/axum/0.8/axum/struct.Form.html /// [`FromRequest`]: crate::extract::FromRequest /// [`RequestBodyLimit`]: tower_http::limit::RequestBodyLimit /// [`RequestExt::with_limited_body`]: crate::RequestExt::with_limited_body /// [`RequestExt::into_limited_body`]: crate::RequestExt::into_limited_body #[derive(Debug, Clone, Copy)] #[must_use] pub struct DefaultBodyLimit { kind: DefaultBodyLimitKind, } #[derive(Debug, Clone, Copy)] pub(crate) enum DefaultBodyLimitKind { Disable, Limit(usize), } impl DefaultBodyLimit { /// Disable the default request body limit. /// /// This must be used to receive bodies larger than the default limit of 2MB using [`Bytes`] or /// an extractor built on it such as `String`, [`Json`], [`Form`]. /// /// Note that if you're accepting data from untrusted remotes it is recommend to add your own /// limit such as [`tower_http::limit`]. /// /// # Example /// /// ``` /// use axum::{ /// Router, /// routing::get, /// body::{Bytes, Body}, /// extract::DefaultBodyLimit, /// }; /// use tower_http::limit::RequestBodyLimitLayer; /// /// let app: Router<()> = Router::new() /// .route("/", get(|body: Bytes| async {})) /// // Disable the default limit /// .layer(DefaultBodyLimit::disable()) /// // Set a different limit /// .layer(RequestBodyLimitLayer::new(10 * 1000 * 1000)); /// ``` /// /// [`Bytes`]: bytes::Bytes /// [`Json`]: https://docs.rs/axum/0.8/axum/struct.Json.html /// [`Form`]: https://docs.rs/axum/0.8/axum/struct.Form.html pub const fn disable() -> Self { Self { kind: DefaultBodyLimitKind::Disable, } } /// Set the default request body limit. /// /// By default the limit of request body sizes that [`Bytes::from_request`] (and other /// extractors built on top of it such as `String`, [`Json`], and [`Form`]) is 2MB. This method /// can be used to change that limit. /// /// # Example /// /// ``` /// use axum::{ /// Router, /// routing::get, /// body::{Bytes, Body}, /// extract::DefaultBodyLimit, /// }; /// /// let app: Router<()> = Router::new() /// .route("/", get(|body: Bytes| async {})) /// // Replace the default of 2MB with 1024 bytes. /// .layer(DefaultBodyLimit::max(1024)); /// ``` /// /// [`Bytes::from_request`]: bytes::Bytes /// [`Json`]: https://docs.rs/axum/0.8/axum/struct.Json.html /// [`Form`]: https://docs.rs/axum/0.8/axum/struct.Form.html pub const fn max(limit: usize) -> Self { Self { kind: DefaultBodyLimitKind::Limit(limit), } } /// Apply a request body limit to the given request. /// /// This can be used, for example, to modify the default body limit inside a specific /// extractor. /// /// # Example /// /// An extractor similar to [`Bytes`](bytes::Bytes), but limiting the body to 1 KB. /// /// ``` /// use axum::{ /// extract::{DefaultBodyLimit, FromRequest, rejection::BytesRejection, Request}, /// body::Bytes, /// }; /// /// struct Bytes1KB(Bytes); /// /// impl<S: Sync> FromRequest<S> for Bytes1KB { /// type Rejection = BytesRejection; /// /// async fn from_request(mut req: Request, _: &S) -> Result<Self, Self::Rejection> { /// DefaultBodyLimit::max(1024).apply(&mut req); /// Ok(Self(Bytes::from_request(req, &()).await?)) /// } /// } /// ``` pub fn apply<B>(self, req: &mut Request<B>) { req.extensions_mut().insert(self.kind); } } impl<S> Layer<S> for DefaultBodyLimit { type Service = DefaultBodyLimitService<S>; fn layer(&self, inner: S) -> Self::Service { DefaultBodyLimitService { inner, kind: self.kind, } } } mod private { use super::DefaultBodyLimitKind; use http::Request; use std::task::Context; use tower_service::Service; #[derive(Debug, Clone, Copy)] pub struct DefaultBodyLimitService<S> { pub(super) inner: S, pub(super) kind: DefaultBodyLimitKind, } impl<B, S> Service<Request<B>> for DefaultBodyLimitService<S> where S: Service<Request<B>>, { type Response = S::Response; type Error = S::Error; type Future = S::Future; #[inline] fn poll_ready(&mut self, cx: &mut Context<'_>) -> std::task::Poll<Result<(), Self::Error>> { self.inner.poll_ready(cx) } #[inline] fn call(&mut self, mut req: Request<B>) -> Self::Future { req.extensions_mut().insert(self.kind); self.inner.call(req) } } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-core/src/extract/request_parts.rs
axum-core/src/extract/request_parts.rs
use super::{rejection::*, FromRequest, FromRequestParts, Request}; use crate::{body::Body, RequestExt}; use bytes::{BufMut, Bytes, BytesMut}; use http::{request::Parts, Extensions, HeaderMap, Method, Uri, Version}; use http_body_util::BodyExt; use std::convert::Infallible; impl<S> FromRequest<S> for Request where S: Send + Sync, { type Rejection = Infallible; async fn from_request(req: Request, _: &S) -> Result<Self, Self::Rejection> { Ok(req) } } impl<S> FromRequestParts<S> for Method where S: Send + Sync, { type Rejection = Infallible; async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> { Ok(parts.method.clone()) } } impl<S> FromRequestParts<S> for Uri where S: Send + Sync, { type Rejection = Infallible; async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> { Ok(parts.uri.clone()) } } impl<S> FromRequestParts<S> for Version where S: Send + Sync, { type Rejection = Infallible; async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> { Ok(parts.version) } } /// Clone the headers from the request. /// /// Prefer using [`TypedHeader`] to extract only the headers you need. /// /// [`TypedHeader`]: https://docs.rs/axum-extra/0.10/axum_extra/struct.TypedHeader.html impl<S> FromRequestParts<S> for HeaderMap where S: Send + Sync, { type Rejection = Infallible; async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, Self::Rejection> { Ok(parts.headers.clone()) } } #[diagnostic::do_not_recommend] // pretty niche impl impl<S> FromRequest<S> for BytesMut where S: Send + Sync, { type Rejection = BytesRejection; async fn from_request(req: Request, _: &S) -> Result<Self, Self::Rejection> { let mut body = req.into_limited_body(); #[allow(clippy::use_self)] let mut bytes = BytesMut::new(); body_to_bytes_mut(&mut body, &mut bytes).await?; Ok(bytes) } } async fn body_to_bytes_mut(body: &mut Body, bytes: &mut BytesMut) -> Result<(), BytesRejection> { while let Some(frame) = body .frame() .await .transpose() .map_err(FailedToBufferBody::from_err)? { let Ok(data) = frame.into_data() else { return Ok(()); }; bytes.put(data); } Ok(()) } impl<S> FromRequest<S> for Bytes where S: Send + Sync, { type Rejection = BytesRejection; async fn from_request(req: Request, _: &S) -> Result<Self, Self::Rejection> { let bytes = req .into_limited_body() .collect() .await .map_err(FailedToBufferBody::from_err)? .to_bytes(); Ok(bytes) } } impl<S> FromRequest<S> for String where S: Send + Sync, { type Rejection = StringRejection; async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> { let bytes = Bytes::from_request(req, state) .await .map_err(|err| match err { BytesRejection::FailedToBufferBody(inner) => { StringRejection::FailedToBufferBody(inner) } })?; #[allow(clippy::use_self)] let string = String::from_utf8(bytes.into()).map_err(InvalidUtf8::from_err)?; Ok(string) } } #[diagnostic::do_not_recommend] // pretty niche impl impl<S> FromRequestParts<S> for Parts where S: Send + Sync, { type Rejection = Infallible; async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> { Ok(parts.clone()) } } #[diagnostic::do_not_recommend] // pretty niche impl impl<S> FromRequestParts<S> for Extensions where S: Send + Sync, { type Rejection = Infallible; async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> { Ok(parts.extensions.clone()) } } impl<S> FromRequest<S> for Body where S: Send + Sync, { type Rejection = Infallible; async fn from_request(req: Request, _: &S) -> Result<Self, Self::Rejection> { Ok(req.into_body()) } } #[cfg(test)] mod tests { use axum::{extract::Extension, routing::get, test_helpers::*, Router}; use http::{Method, StatusCode}; #[crate::test] async fn extract_request_parts() { #[derive(Clone)] struct Ext; async fn handler(parts: http::request::Parts) { assert_eq!(parts.method, Method::GET); assert_eq!(parts.uri, "/"); assert_eq!(parts.version, http::Version::HTTP_11); assert_eq!(parts.headers["x-foo"], "123"); parts.extensions.get::<Ext>().unwrap(); } let client = TestClient::new(Router::new().route("/", get(handler)).layer(Extension(Ext))); let res = client.get("/").header("x-foo", "123").await; assert_eq!(res.status(), StatusCode::OK); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-core/src/extract/from_ref.rs
axum-core/src/extract/from_ref.rs
/// Used to do reference-to-value conversions thus not consuming the input value. /// /// This is mainly used with [`State`] to extract "substates" from a reference to main application /// state. /// /// See [`State`] for more details on how library authors should use this trait. /// /// This trait can be derived using `#[derive(FromRef)]`. /// /// [`State`]: https://docs.rs/axum/0.8/axum/extract/struct.State.html // NOTE: This trait is defined in axum-core, even though it is mainly used with `State` which is // defined in axum. That allows crate authors to use it when implementing extractors. pub trait FromRef<T> { /// Converts to this type from a reference to the input type. fn from_ref(input: &T) -> Self; } impl<T> FromRef<T> for T where T: Clone, { fn from_ref(input: &T) -> Self { input.clone() } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-core/src/extract/tuple.rs
axum-core/src/extract/tuple.rs
use super::{FromRequest, FromRequestParts, Request}; use crate::response::{IntoResponse, Response}; use http::request::Parts; use std::{convert::Infallible, future::Future}; #[diagnostic::do_not_recommend] impl<S> FromRequestParts<S> for () where S: Send + Sync, { type Rejection = Infallible; async fn from_request_parts(_: &mut Parts, _: &S) -> Result<(), Self::Rejection> { Ok(()) } } macro_rules! impl_from_request { ( [$($ty:ident),*], $last:ident ) => { #[diagnostic::do_not_recommend] #[allow(non_snake_case, unused_mut, unused_variables)] impl<S, $($ty,)* $last> FromRequestParts<S> for ($($ty,)* $last,) where $( $ty: FromRequestParts<S> + Send, )* $last: FromRequestParts<S> + Send, S: Send + Sync, { type Rejection = Response; async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { $( let $ty = $ty::from_request_parts(parts, state) .await .map_err(|err| err.into_response())?; )* let $last = $last::from_request_parts(parts, state) .await .map_err(|err| err.into_response())?; Ok(($($ty,)* $last,)) } } // This impl must not be generic over M, otherwise it would conflict with the blanket // implementation of `FromRequest<S, Mut>` for `T: FromRequestParts<S>`. #[diagnostic::do_not_recommend] #[allow(non_snake_case, unused_mut, unused_variables)] impl<S, $($ty,)* $last> FromRequest<S> for ($($ty,)* $last,) where $( $ty: FromRequestParts<S> + Send, )* $last: FromRequest<S> + Send, S: Send + Sync, { type Rejection = Response; fn from_request(req: Request, state: &S) -> impl Future<Output = Result<Self, Self::Rejection>> { let (mut parts, body) = req.into_parts(); async move { $( let $ty = $ty::from_request_parts(&mut parts, state).await.map_err(|err| err.into_response())?; )* let req = Request::from_parts(parts, body); let $last = $last::from_request(req, state).await.map_err(|err| err.into_response())?; Ok(($($ty,)* $last,)) } } } }; } all_the_tuples!(impl_from_request); #[cfg(test)] mod tests { use bytes::Bytes; use http::Method; use crate::extract::{FromRequest, FromRequestParts}; fn assert_from_request<M, T>() where T: FromRequest<(), M>, { } fn assert_from_request_parts<T: FromRequestParts<()>>() {} #[test] fn unit() { assert_from_request_parts::<()>(); assert_from_request::<_, ()>(); } #[test] fn tuple_of_one() { assert_from_request_parts::<(Method,)>(); assert_from_request::<_, (Method,)>(); assert_from_request::<_, (Bytes,)>(); } #[test] fn tuple_of_two() { assert_from_request_parts::<((), ())>(); assert_from_request::<_, ((), ())>(); assert_from_request::<_, (Method, Bytes)>(); } #[test] fn nested_tuple() { assert_from_request_parts::<(((Method,),),)>(); assert_from_request::<_, ((((Bytes,),),),)>(); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-core/src/extract/option.rs
axum-core/src/extract/option.rs
use std::future::Future; use http::request::Parts; use crate::response::IntoResponse; use super::{private, FromRequest, FromRequestParts, Request}; /// Customize the behavior of `Option<Self>` as a [`FromRequestParts`] /// extractor. pub trait OptionalFromRequestParts<S>: Sized { /// If the extractor fails, it will use this "rejection" type. /// /// A rejection is a kind of error that can be converted into a response. type Rejection: IntoResponse; /// Perform the extraction. fn from_request_parts( parts: &mut Parts, state: &S, ) -> impl Future<Output = Result<Option<Self>, Self::Rejection>> + Send; } /// Customize the behavior of `Option<Self>` as a [`FromRequest`] extractor. pub trait OptionalFromRequest<S, M = private::ViaRequest>: Sized { /// If the extractor fails, it will use this "rejection" type. /// /// A rejection is a kind of error that can be converted into a response. type Rejection: IntoResponse; /// Perform the extraction. fn from_request( req: Request, state: &S, ) -> impl Future<Output = Result<Option<Self>, Self::Rejection>> + Send; } // Compiler hint just says that there is an impl for Option<T>, not mentioning // the bounds, which is not very helpful. #[diagnostic::do_not_recommend] impl<S, T> FromRequestParts<S> for Option<T> where T: OptionalFromRequestParts<S>, S: Send + Sync, { type Rejection = T::Rejection; #[allow(clippy::use_self)] fn from_request_parts( parts: &mut Parts, state: &S, ) -> impl Future<Output = Result<Option<T>, Self::Rejection>> { T::from_request_parts(parts, state) } } #[diagnostic::do_not_recommend] impl<S, T> FromRequest<S> for Option<T> where T: OptionalFromRequest<S>, S: Send + Sync, { type Rejection = T::Rejection; #[allow(clippy::use_self)] async fn from_request(req: Request, state: &S) -> Result<Option<T>, Self::Rejection> { T::from_request(req, state).await } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-core/src/extract/mod.rs
axum-core/src/extract/mod.rs
//! Types and traits for extracting data from requests. //! //! See [`axum::extract`] for more details. //! //! [`axum::extract`]: https://docs.rs/axum/0.8/axum/extract/index.html use crate::{body::Body, response::IntoResponse}; use http::request::Parts; use std::convert::Infallible; use std::future::Future; pub mod rejection; mod default_body_limit; mod from_ref; mod option; mod request_parts; mod tuple; pub(crate) use self::default_body_limit::DefaultBodyLimitKind; pub use self::{ default_body_limit::DefaultBodyLimit, from_ref::FromRef, option::{OptionalFromRequest, OptionalFromRequestParts}, }; /// Type alias for [`http::Request`] whose body type defaults to [`Body`], the most common body /// type used with axum. pub type Request<T = Body> = http::Request<T>; mod private { #[derive(Debug, Clone, Copy)] pub enum ViaParts {} #[derive(Debug, Clone, Copy)] pub enum ViaRequest {} } /// Types that can be created from request parts. /// /// Extractors that implement `FromRequestParts` cannot consume the request body and can thus be /// run in any order for handlers. /// /// If your extractor needs to consume the request body then you should implement [`FromRequest`] /// and not [`FromRequestParts`]. /// /// See [`axum::extract`] for more general docs about extractors. /// /// [`axum::extract`]: https://docs.rs/axum/0.8/axum/extract/index.html #[diagnostic::on_unimplemented( note = "Function argument is not a valid axum extractor. \nSee `https://docs.rs/axum/0.8/axum/extract/index.html` for details" )] pub trait FromRequestParts<S>: 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. fn from_request_parts( parts: &mut Parts, state: &S, ) -> impl Future<Output = Result<Self, Self::Rejection>> + Send; } /// Types that can be created from requests. /// /// Extractors that implement `FromRequest` can consume the request body and can thus only be run /// once for handlers. /// /// If your extractor doesn't need to consume the request body then you should implement /// [`FromRequestParts`] and not [`FromRequest`]. /// /// See [`axum::extract`] for more general docs about extractors. /// /// [`axum::extract`]: https://docs.rs/axum/0.8/axum/extract/index.html #[diagnostic::on_unimplemented( note = "Function argument is not a valid axum extractor. \nSee `https://docs.rs/axum/0.8/axum/extract/index.html` for details" )] pub trait FromRequest<S, M = private::ViaRequest>: 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. fn from_request( req: Request, state: &S, ) -> impl Future<Output = Result<Self, Self::Rejection>> + Send; } impl<S, T> FromRequest<S, private::ViaParts> for T where S: Send + Sync, T: FromRequestParts<S>, { type Rejection = <Self as FromRequestParts<S>>::Rejection; fn from_request( req: Request, state: &S, ) -> impl Future<Output = Result<Self, Self::Rejection>> { let (mut parts, _) = req.into_parts(); async move { Self::from_request_parts(&mut parts, state).await } } } impl<S, T> FromRequestParts<S> for Result<T, T::Rejection> where T: FromRequestParts<S>, S: Send + Sync, { type Rejection = Infallible; async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { Ok(T::from_request_parts(parts, state).await) } } impl<S, T> FromRequest<S> for Result<T, T::Rejection> where T: FromRequest<S>, S: Send + Sync, { type Rejection = Infallible; async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> { Ok(T::from_request(req, state).await) } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-core/src/extract/rejection.rs
axum-core/src/extract/rejection.rs
//! Rejection response types. use crate::__composite_rejection as composite_rejection; use crate::__define_rejection as define_rejection; use crate::{BoxError, Error}; composite_rejection! { /// Rejection type for extractors that buffer the request body. Used if the /// request body cannot be buffered due to an error. pub enum FailedToBufferBody { LengthLimitError, UnknownBodyError, } } impl FailedToBufferBody { pub(crate) fn from_err<E>(err: E) -> Self where E: Into<BoxError>, { // two layers of boxes here because `with_limited_body` // wraps the `http_body_util::Limited` in a `axum_core::Body` // which also wraps the error type let box_error = match err.into().downcast::<Error>() { Ok(err) => err.into_inner(), Err(err) => err, }; let box_error = match box_error.downcast::<Error>() { Ok(err) => err.into_inner(), Err(err) => err, }; match box_error.downcast::<http_body_util::LengthLimitError>() { Ok(err) => Self::LengthLimitError(LengthLimitError::from_err(err)), Err(err) => Self::UnknownBodyError(UnknownBodyError::from_err(err)), } } } define_rejection! { #[status = PAYLOAD_TOO_LARGE] #[body = "Failed to buffer the request body"] /// Encountered some other error when buffering the body. /// /// This can _only_ happen when you're using [`tower_http::limit::RequestBodyLimitLayer`] or /// otherwise wrapping request bodies in [`http_body_util::Limited`]. pub struct LengthLimitError(Error); } define_rejection! { #[status = BAD_REQUEST] #[body = "Failed to buffer the request body"] /// Encountered an unknown error when buffering the body. pub struct UnknownBodyError(Error); } define_rejection! { #[status = BAD_REQUEST] #[body = "Request body didn't contain valid UTF-8"] /// Rejection type used when buffering the request into a [`String`] if the /// body doesn't contain valid UTF-8. pub struct InvalidUtf8(Error); } composite_rejection! { /// Rejection used for [`Bytes`](bytes::Bytes). /// /// Contains one variant for each way the [`Bytes`](bytes::Bytes) extractor /// can fail. pub enum BytesRejection { FailedToBufferBody, } } composite_rejection! { /// Rejection used for [`String`]. /// /// Contains one variant for each way the [`String`] extractor can fail. pub enum StringRejection { FailedToBufferBody, InvalidUtf8, } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-core/src/response/append_headers.rs
axum-core/src/response/append_headers.rs
use super::{IntoResponse, IntoResponseParts, Response, ResponseParts, TryIntoHeaderError}; use http::header::{HeaderName, HeaderValue}; use std::fmt; /// Append headers to a response. /// /// Returning something like `[("content-type", "foo=bar")]` from a handler will override any /// existing `content-type` headers. If instead you want to append headers, use `AppendHeaders`: /// /// ```rust /// use axum::{ /// response::{AppendHeaders, IntoResponse}, /// http::header::SET_COOKIE, /// }; /// /// async fn handler() -> impl IntoResponse { /// // something that sets the `set-cookie` header /// let set_some_cookies = /* ... */ /// # axum::http::HeaderMap::new(); /// /// ( /// set_some_cookies, /// // append two `set-cookie` headers to the response /// // without overriding the ones added by `set_some_cookies` /// AppendHeaders([ /// (SET_COOKIE, "foo=bar"), /// (SET_COOKIE, "baz=qux"), /// ]) /// ) /// } /// ``` #[derive(Debug, Clone, Copy)] #[must_use] pub struct AppendHeaders<I>(pub I); impl<I, K, V> IntoResponse for AppendHeaders<I> where I: IntoIterator<Item = (K, V)>, K: TryInto<HeaderName>, K::Error: fmt::Display, V: TryInto<HeaderValue>, V::Error: fmt::Display, { fn into_response(self) -> Response { (self, ()).into_response() } } impl<I, K, V> IntoResponseParts for AppendHeaders<I> where I: IntoIterator<Item = (K, V)>, K: TryInto<HeaderName>, K::Error: fmt::Display, V: TryInto<HeaderValue>, V::Error: fmt::Display, { type Error = TryIntoHeaderError<K::Error, V::Error>; fn into_response_parts(self, mut res: ResponseParts) -> Result<ResponseParts, Self::Error> { for (key, value) in self.0 { let key = key.try_into().map_err(TryIntoHeaderError::key)?; let value = value.try_into().map_err(TryIntoHeaderError::value)?; res.headers_mut().append(key, value); } Ok(res) } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-core/src/response/into_response.rs
axum-core/src/response/into_response.rs
use super::{IntoResponseParts, Response, ResponseParts}; use crate::{body::Body, BoxError}; use bytes::{buf::Chain, Buf, Bytes, BytesMut}; use http::{ header::{self, HeaderMap, HeaderName, HeaderValue}, Extensions, StatusCode, }; use http_body::{Frame, SizeHint}; use std::{ borrow::Cow, convert::Infallible, fmt, pin::Pin, task::{Context, Poll}, }; /// Trait for generating responses. /// /// Types that implement `IntoResponse` can be returned from handlers. /// /// # Implementing `IntoResponse` /// /// You generally shouldn't have to implement `IntoResponse` manually, as axum /// provides implementations for many common types. /// /// However it might be necessary if you have a custom error type that you want /// to return from handlers: /// /// ```rust /// use axum::{ /// Router, /// body::{self, Bytes}, /// routing::get, /// http::StatusCode, /// response::{IntoResponse, Response}, /// }; /// /// enum MyError { /// SomethingWentWrong, /// SomethingElseWentWrong, /// } /// /// impl IntoResponse for MyError { /// fn into_response(self) -> Response { /// let body = match self { /// MyError::SomethingWentWrong => "something went wrong", /// MyError::SomethingElseWentWrong => "something else went wrong", /// }; /// /// // it's often easiest to implement `IntoResponse` by calling other implementations /// (StatusCode::INTERNAL_SERVER_ERROR, body).into_response() /// } /// } /// /// // `Result<impl IntoResponse, MyError>` can now be returned from handlers /// let app = Router::new().route("/", get(handler)); /// /// async fn handler() -> Result<(), MyError> { /// Err(MyError::SomethingWentWrong) /// } /// # let _: Router = app; /// ``` /// /// Or if you have a custom body type you'll also need to implement /// `IntoResponse` for it: /// /// ```rust /// use axum::{ /// body, /// routing::get, /// response::{IntoResponse, Response}, /// body::Body, /// Router, /// }; /// use http::HeaderMap; /// use bytes::Bytes; /// use http_body::Frame; /// use std::{ /// convert::Infallible, /// task::{Poll, Context}, /// pin::Pin, /// }; /// /// struct MyBody; /// /// // First implement `Body` for `MyBody`. This could for example use /// // some custom streaming protocol. /// impl http_body::Body for MyBody { /// type Data = Bytes; /// type Error = Infallible; /// /// fn poll_frame( /// self: Pin<&mut Self>, /// cx: &mut Context<'_>, /// ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> { /// # unimplemented!() /// // ... /// } /// } /// /// // Now we can implement `IntoResponse` directly for `MyBody` /// impl IntoResponse for MyBody { /// fn into_response(self) -> Response { /// Response::new(Body::new(self)) /// } /// } /// /// // `MyBody` can now be returned from handlers. /// let app = Router::new().route("/", get(|| async { MyBody })); /// # let _: Router = app; /// ``` pub trait IntoResponse { /// Create a response. #[must_use] fn into_response(self) -> Response; } impl IntoResponse for StatusCode { fn into_response(self) -> Response { let mut res = ().into_response(); *res.status_mut() = self; res } } impl IntoResponse for () { fn into_response(self) -> Response { Body::empty().into_response() } } impl IntoResponse for Infallible { fn into_response(self) -> Response { match self {} } } impl<T, E> IntoResponse for Result<T, E> where T: IntoResponse, E: IntoResponse, { fn into_response(self) -> Response { match self { Ok(value) => value.into_response(), Err(err) => err.into_response(), } } } impl<B> IntoResponse for Response<B> where B: http_body::Body<Data = Bytes> + Send + 'static, B::Error: Into<BoxError>, { fn into_response(self) -> Response { self.map(Body::new) } } impl IntoResponse for http::response::Parts { fn into_response(self) -> Response { Response::from_parts(self, Body::empty()) } } impl IntoResponse for Body { fn into_response(self) -> Response { Response::new(self) } } impl IntoResponse for &'static str { fn into_response(self) -> Response { Cow::Borrowed(self).into_response() } } impl IntoResponse for String { fn into_response(self) -> Response { Cow::<'static, str>::Owned(self).into_response() } } impl IntoResponse for Box<str> { fn into_response(self) -> Response { String::from(self).into_response() } } impl IntoResponse for Cow<'static, str> { fn into_response(self) -> 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()), ); res } } impl IntoResponse for Bytes { fn into_response(self) -> 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()), ); res } } impl IntoResponse for BytesMut { fn into_response(self) -> Response { self.freeze().into_response() } } impl<T, U> IntoResponse for Chain<T, U> where T: Buf + Unpin + Send + 'static, U: Buf + Unpin + Send + 'static, { fn into_response(self) -> Response { let (first, second) = self.into_inner(); let mut res = Response::new(Body::new(BytesChainBody { first: Some(first), second: Some(second), })); res.headers_mut().insert( header::CONTENT_TYPE, HeaderValue::from_static(mime::APPLICATION_OCTET_STREAM.as_ref()), ); res } } struct BytesChainBody<T, U> { first: Option<T>, second: Option<U>, } impl<T, U> http_body::Body for BytesChainBody<T, U> where T: Buf + Unpin, U: Buf + Unpin, { type Data = Bytes; type Error = Infallible; fn poll_frame( mut self: Pin<&mut Self>, _cx: &mut Context<'_>, ) -> Poll<Option<Result<Frame<Self::Data>, Self::Error>>> { if let Some(mut buf) = self.first.take() { let bytes = buf.copy_to_bytes(buf.remaining()); return Poll::Ready(Some(Ok(Frame::data(bytes)))); } if let Some(mut buf) = self.second.take() { let bytes = buf.copy_to_bytes(buf.remaining()); return Poll::Ready(Some(Ok(Frame::data(bytes)))); } Poll::Ready(None) } fn is_end_stream(&self) -> bool { self.first.is_none() && self.second.is_none() } fn size_hint(&self) -> SizeHint { match (self.first.as_ref(), self.second.as_ref()) { (Some(first), Some(second)) => { let total_size = first.remaining() + second.remaining(); SizeHint::with_exact(total_size as u64) } (Some(buf), None) => SizeHint::with_exact(buf.remaining() as u64), (None, Some(buf)) => SizeHint::with_exact(buf.remaining() as u64), (None, None) => SizeHint::with_exact(0), } } } impl IntoResponse for &'static [u8] { fn into_response(self) -> Response { Cow::Borrowed(self).into_response() } } impl<const N: usize> IntoResponse for &'static [u8; N] { fn into_response(self) -> Response { self.as_slice().into_response() } } impl<const N: usize> IntoResponse for [u8; N] { fn into_response(self) -> Response { self.to_vec().into_response() } } impl IntoResponse for Vec<u8> { fn into_response(self) -> Response { Cow::<'static, [u8]>::Owned(self).into_response() } } impl IntoResponse for Box<[u8]> { fn into_response(self) -> Response { Vec::from(self).into_response() } } impl IntoResponse for Cow<'static, [u8]> { fn into_response(self) -> 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()), ); res } } impl<R> IntoResponse for (StatusCode, R) where R: IntoResponse, { fn into_response(self) -> Response { let mut res = self.1.into_response(); *res.status_mut() = self.0; res } } impl IntoResponse for HeaderMap { fn into_response(self) -> Response { let mut res = ().into_response(); *res.headers_mut() = self; res } } impl IntoResponse for Extensions { fn into_response(self) -> Response { let mut res = ().into_response(); *res.extensions_mut() = self; res } } impl<K, V, const N: usize> IntoResponse for [(K, V); N] where K: TryInto<HeaderName>, K::Error: fmt::Display, V: TryInto<HeaderValue>, V::Error: fmt::Display, { fn into_response(self) -> Response { (self, ()).into_response() } } impl<R> IntoResponse for (http::response::Parts, R) where R: IntoResponse, { fn into_response(self) -> Response { let (parts, res) = self; (parts.status, parts.headers, parts.extensions, res).into_response() } } impl<R> IntoResponse for (http::response::Response<()>, R) where R: IntoResponse, { fn into_response(self) -> Response { let (template, res) = self; let (parts, ()) = template.into_parts(); (parts, res).into_response() } } impl<R> IntoResponse for (R,) where R: IntoResponse, { fn into_response(self) -> Response { let (res,) = self; res.into_response() } } macro_rules! impl_into_response { ( $($ty:ident),* $(,)? ) => { #[allow(non_snake_case)] impl<R, $($ty,)*> IntoResponse for ($($ty),*, R) where $( $ty: IntoResponseParts, )* R: IntoResponse, { fn into_response(self) -> Response { let ($($ty),*, res) = self; let res = res.into_response(); let parts = ResponseParts { res }; $( let parts = match $ty.into_response_parts(parts) { Ok(parts) => parts, Err(err) => { return err.into_response(); } }; )* parts.res } } #[allow(non_snake_case)] impl<R, $($ty,)*> IntoResponse for (StatusCode, $($ty),*, R) where $( $ty: IntoResponseParts, )* R: IntoResponse, { fn into_response(self) -> Response { let (status, $($ty),*, res) = self; let res = res.into_response(); let parts = ResponseParts { res }; $( let parts = match $ty.into_response_parts(parts) { Ok(parts) => parts, Err(err) => { return err.into_response(); } }; )* (status, parts.res).into_response() } } #[allow(non_snake_case)] impl<R, $($ty,)*> IntoResponse for (http::response::Parts, $($ty),*, R) where $( $ty: IntoResponseParts, )* R: IntoResponse, { fn into_response(self) -> Response { let (outer_parts, $($ty),*, res) = self; let res = res.into_response(); let parts = ResponseParts { res }; $( let parts = match $ty.into_response_parts(parts) { Ok(parts) => parts, Err(err) => { return err.into_response(); } }; )* (outer_parts, parts.res).into_response() } } #[allow(non_snake_case)] impl<R, $($ty,)*> IntoResponse for (http::response::Response<()>, $($ty),*, R) where $( $ty: IntoResponseParts, )* R: IntoResponse, { fn into_response(self) -> Response { let (template, $($ty),*, res) = self; let (parts, ()) = template.into_parts(); (parts, $($ty),*, res).into_response() } } } } all_the_tuples_no_last_special_case!(impl_into_response);
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-core/src/response/mod.rs
axum-core/src/response/mod.rs
//! Types and traits for generating responses. //! //! See [`axum::response`] for more details. //! //! [`axum::response`]: https://docs.rs/axum/0.8/axum/response/index.html use crate::body::Body; mod append_headers; mod into_response; mod into_response_parts; pub use self::{ append_headers::AppendHeaders, into_response::IntoResponse, into_response_parts::{IntoResponseParts, ResponseParts, TryIntoHeaderError}, }; /// Type alias for [`http::Response`] whose body type defaults to [`Body`], the most common body /// type used with axum. pub type Response<T = Body> = http::Response<T>; /// An [`IntoResponse`]-based result type that uses [`ErrorResponse`] as the error type. /// /// All types which implement [`IntoResponse`] can be converted to an [`ErrorResponse`]. This makes /// it useful as a general purpose error type for functions which combine multiple distinct error /// types that all implement [`IntoResponse`]. /// /// # Example /// /// ``` /// use axum::{ /// response::{IntoResponse, Response}, /// http::StatusCode, /// }; /// /// // two fallible functions with different error types /// fn try_something() -> Result<(), ErrorA> { /// // ... /// # unimplemented!() /// } /// /// fn try_something_else() -> Result<(), ErrorB> { /// // ... /// # unimplemented!() /// } /// /// // each error type implements `IntoResponse` /// struct ErrorA; /// /// impl IntoResponse for ErrorA { /// fn into_response(self) -> Response { /// // ... /// # unimplemented!() /// } /// } /// /// enum ErrorB { /// SomethingWentWrong, /// } /// /// impl IntoResponse for ErrorB { /// fn into_response(self) -> Response { /// // ... /// # unimplemented!() /// } /// } /// /// // we can combine them using `axum::response::Result` and still use `?` /// async fn handler() -> axum::response::Result<&'static str> { /// // the errors are automatically converted to `ErrorResponse` /// try_something()?; /// try_something_else()?; /// /// Ok("it worked!") /// } /// ``` /// /// # As a replacement for `std::result::Result` /// /// Since `axum::response::Result` has a default error type you only have to specify the `Ok` type: /// /// ``` /// use axum::{ /// response::{IntoResponse, Response, Result}, /// http::StatusCode, /// }; /// /// // `Result<T>` automatically uses `ErrorResponse` as the error type. /// async fn handler() -> Result<&'static str> { /// try_something()?; /// /// Ok("it worked!") /// } /// /// // You can still specify the error even if you've imported `axum::response::Result` /// fn try_something() -> Result<(), StatusCode> { /// // ... /// # unimplemented!() /// } /// ``` pub type Result<T, E = ErrorResponse> = std::result::Result<T, E>; impl<T> IntoResponse for Result<T> where T: IntoResponse, { fn into_response(self) -> Response { match self { Ok(ok) => ok.into_response(), Err(err) => err.0, } } } /// An [`IntoResponse`]-based error type /// /// See [`Result`] for more details. #[derive(Debug)] #[must_use] pub struct ErrorResponse(Response); impl<T> From<T> for ErrorResponse where T: IntoResponse, { fn from(value: T) -> Self { Self(value.into_response()) } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-core/src/response/into_response_parts.rs
axum-core/src/response/into_response_parts.rs
use super::{IntoResponse, Response}; use http::{ header::{HeaderMap, HeaderName, HeaderValue}, Extensions, StatusCode, }; use std::{convert::Infallible, fmt}; /// Trait for adding headers and extensions to a response. /// /// # Example /// /// ```rust /// use axum::{ /// response::{ResponseParts, IntoResponse, IntoResponseParts, Response}, /// http::{StatusCode, header::{HeaderName, HeaderValue}}, /// }; /// /// // Hypothetical helper type for setting a single header /// struct SetHeader<'a>(&'a str, &'a str); /// /// impl<'a> IntoResponseParts for SetHeader<'a> { /// type Error = (StatusCode, String); /// /// fn into_response_parts(self, mut res: ResponseParts) -> Result<ResponseParts, Self::Error> { /// match (self.0.parse::<HeaderName>(), self.1.parse::<HeaderValue>()) { /// (Ok(name), Ok(value)) => { /// res.headers_mut().insert(name, value); /// }, /// (Err(_), _) => { /// return Err(( /// StatusCode::INTERNAL_SERVER_ERROR, /// format!("Invalid header name {}", self.0), /// )); /// }, /// (_, Err(_)) => { /// return Err(( /// StatusCode::INTERNAL_SERVER_ERROR, /// format!("Invalid header value {}", self.1), /// )); /// }, /// } /// /// Ok(res) /// } /// } /// /// // It's also recommended to implement `IntoResponse` so `SetHeader` can be used on its own as /// // the response /// impl<'a> IntoResponse for SetHeader<'a> { /// fn into_response(self) -> Response { /// // This gives an empty response with the header /// (self, ()).into_response() /// } /// } /// /// // We can now return `SetHeader` in responses /// // /// // Note that returning `impl IntoResponse` might be easier if the response has many parts to /// // it. The return type is written out here for clarity. /// async fn handler() -> (SetHeader<'static>, SetHeader<'static>, &'static str) { /// ( /// SetHeader("server", "axum"), /// SetHeader("x-foo", "custom"), /// "body", /// ) /// } /// /// // Or on its own as the whole response /// async fn other_handler() -> SetHeader<'static> { /// SetHeader("x-foo", "custom") /// } /// ``` pub trait IntoResponseParts { /// The type returned in the event of an error. /// /// This can be used to fallibly convert types into headers or extensions. type Error: IntoResponse; /// Set parts of the response fn into_response_parts(self, res: ResponseParts) -> Result<ResponseParts, Self::Error>; } impl<T> IntoResponseParts for Option<T> where T: IntoResponseParts, { type Error = T::Error; fn into_response_parts(self, res: ResponseParts) -> Result<ResponseParts, Self::Error> { if let Some(inner) = self { inner.into_response_parts(res) } else { Ok(res) } } } /// Parts of a response. /// /// Used with [`IntoResponseParts`]. #[derive(Debug)] pub struct ResponseParts { pub(crate) res: Response, } impl ResponseParts { /// Gets a reference to the response headers. #[must_use] pub fn headers(&self) -> &HeaderMap { self.res.headers() } /// Gets a mutable reference to the response headers. #[must_use] pub fn headers_mut(&mut self) -> &mut HeaderMap { self.res.headers_mut() } /// Gets a reference to the response extensions. #[must_use] pub fn extensions(&self) -> &Extensions { self.res.extensions() } /// Gets a mutable reference to the response extensions. #[must_use] pub fn extensions_mut(&mut self) -> &mut Extensions { self.res.extensions_mut() } } impl IntoResponseParts for HeaderMap { type Error = Infallible; fn into_response_parts(self, mut res: ResponseParts) -> Result<ResponseParts, Self::Error> { res.headers_mut().extend(self); Ok(res) } } impl<K, V, const N: usize> IntoResponseParts for [(K, V); N] where K: TryInto<HeaderName>, K::Error: fmt::Display, V: TryInto<HeaderValue>, V::Error: fmt::Display, { type Error = TryIntoHeaderError<K::Error, V::Error>; fn into_response_parts(self, mut res: ResponseParts) -> Result<ResponseParts, Self::Error> { for (key, value) in self { let key = key.try_into().map_err(TryIntoHeaderError::key)?; let value = value.try_into().map_err(TryIntoHeaderError::value)?; res.headers_mut().insert(key, value); } Ok(res) } } /// Error returned if converting a value to a header fails. #[derive(Debug)] pub struct TryIntoHeaderError<K, V> { kind: TryIntoHeaderErrorKind<K, V>, } impl<K, V> TryIntoHeaderError<K, V> { pub(super) fn key(err: K) -> Self { Self { kind: TryIntoHeaderErrorKind::Key(err), } } pub(super) fn value(err: V) -> Self { Self { kind: TryIntoHeaderErrorKind::Value(err), } } } #[derive(Debug)] enum TryIntoHeaderErrorKind<K, V> { Key(K), Value(V), } impl<K, V> IntoResponse for TryIntoHeaderError<K, V> where K: fmt::Display, V: fmt::Display, { fn into_response(self) -> Response { match self.kind { TryIntoHeaderErrorKind::Key(inner) => { (StatusCode::INTERNAL_SERVER_ERROR, inner.to_string()).into_response() } TryIntoHeaderErrorKind::Value(inner) => { (StatusCode::INTERNAL_SERVER_ERROR, inner.to_string()).into_response() } } } } impl<K, V> fmt::Display for TryIntoHeaderError<K, V> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self.kind { TryIntoHeaderErrorKind::Key(_) => write!(f, "failed to convert key to a header name"), TryIntoHeaderErrorKind::Value(_) => { write!(f, "failed to convert value to a header value") } } } } impl<K, V> std::error::Error for TryIntoHeaderError<K, V> where K: std::error::Error + 'static, V: std::error::Error + 'static, { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.kind { TryIntoHeaderErrorKind::Key(inner) => Some(inner), TryIntoHeaderErrorKind::Value(inner) => Some(inner), } } } macro_rules! impl_into_response_parts { ( $($ty:ident),* $(,)? ) => { #[allow(non_snake_case)] impl<$($ty,)*> IntoResponseParts for ($($ty,)*) where $( $ty: IntoResponseParts, )* { type Error = Response; fn into_response_parts(self, res: ResponseParts) -> Result<ResponseParts, Self::Error> { let ($($ty,)*) = self; $( let res = match $ty.into_response_parts(res) { Ok(res) => res, Err(err) => { return Err(err.into_response()); } }; )* Ok(res) } } } } all_the_tuples_no_last_special_case!(impl_into_response_parts); impl IntoResponseParts for Extensions { type Error = Infallible; fn into_response_parts(self, mut res: ResponseParts) -> Result<ResponseParts, Self::Error> { res.extensions_mut().extend(self); Ok(res) } } impl IntoResponseParts for () { type Error = Infallible; fn into_response_parts(self, res: ResponseParts) -> Result<ResponseParts, Self::Error> { Ok(res) } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/lib.rs
axum-extra/src/lib.rs
//! Extra utilities for [`axum`]. //! //! # Feature flags //! //! axum-extra uses a set of [feature flags] to reduce the amount of compiled and //! optional dependencies. //! //! The following optional features are available: //! //! Name | Description | Default? //! ---|---|--- //! `async-read-body` | Enables the [`AsyncReadBody`](crate::body::AsyncReadBody) body | //! `attachment` | Enables the [`Attachment`](crate::response::Attachment) response | //! `cached` | Enables the [`Cached`](crate::extract::Cached) extractor | //! `cookie` | Enables the [`CookieJar`](crate::extract::CookieJar) extractor | //! `cookie-private` | Enables the [`PrivateCookieJar`](crate::extract::PrivateCookieJar) extractor | //! `cookie-signed` | Enables the [`SignedCookieJar`](crate::extract::SignedCookieJar) extractor | //! `cookie-key-expansion` | Enables the [`Key::derive_from`](crate::extract::cookie::Key::derive_from) method | //! `erased-json` | Enables the [`ErasedJson`](crate::response::ErasedJson) response | //! `error-response` | Enables the [`InternalServerError`](crate::response::InternalServerError) response | //! `form` (deprecated) | Enables the [`Form`](crate::extract::Form) extractor | //! `handler` | Enables the [handler] utilities | //! `json-deserializer` | Enables the [`JsonDeserializer`](crate::extract::JsonDeserializer) extractor | //! `json-lines` | Enables the [`JsonLines`](crate::extract::JsonLines) extractor and response | //! `middleware` | Enables the [middleware] utilities | //! `multipart` | Enables the [`Multipart`](crate::extract::Multipart) extractor | //! `protobuf` | Enables the [`Protobuf`](crate::protobuf::Protobuf) extractor and response | //! `query` (deprecated) | Enables the [`Query`](crate::extract::Query) extractor | //! `routing` | Enables the [routing] utilities | //! `tracing` | Log rejections from built-in extractors | <span role="img" aria-label="Default feature">✔</span> //! `typed-routing` | Enables the [`TypedPath`](crate::routing::TypedPath) routing utilities and the `routing` feature. | //! `typed-header` | Enables the [`TypedHeader`] extractor and response | //! `file-stream` | Enables the [`FileStream`](crate::response::FileStream) response | //! `with-rejection` | Enables the [`WithRejection`](crate::extract::WithRejection) extractor | //! //! [`axum`]: https://crates.io/crates/axum #![cfg_attr(docsrs, feature(doc_cfg))] #![cfg_attr(test, allow(clippy::float_cmp))] #![cfg_attr(not(test), warn(clippy::print_stdout, clippy::dbg_macro))] #[allow(unused_extern_crates)] extern crate self as axum_extra; pub mod body; pub mod either; pub mod extract; pub mod response; #[cfg(feature = "routing")] pub mod routing; #[cfg(feature = "middleware")] pub mod middleware; #[cfg(feature = "handler")] pub mod handler; #[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; /// _not_ public API #[cfg(feature = "typed-routing")] #[doc(hidden)] pub mod __private { use percent_encoding::{AsciiSet, CONTROLS}; pub use percent_encoding::utf8_percent_encode; // from https://github.com/servo/rust-url/blob/master/url/src/parser.rs const FRAGMENT: &AsciiSet = &CONTROLS.add(b' ').add(b'"').add(b'<').add(b'>').add(b'`'); const PATH: &AsciiSet = &FRAGMENT.add(b'#').add(b'?').add(b'{').add(b'}'); pub const PATH_SEGMENT: &AsciiSet = &PATH.add(b'/').add(b'%'); } #[cfg(test)] pub(crate) use axum::test_helpers;
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/middleware.rs
axum-extra/src/middleware.rs
//! Additional middleware utilities. use crate::either::Either; use axum::middleware::ResponseAxumBodyLayer; use tower_layer::Identity; /// Convert an `Option<Layer>` into a [`Layer`]. /// /// If the layer is a `Some` it'll be applied, otherwise not. /// /// # Example /// /// ``` /// use axum_extra::middleware::option_layer; /// use axum::{Router, routing::get}; /// use std::time::Duration; /// use tower_http::timeout::TimeoutLayer; /// /// # let option_timeout = Some(Duration::new(10, 0)); /// let timeout_layer = option_timeout.map(TimeoutLayer::new); /// /// let app = Router::new() /// .route("/", get(|| async {})) /// .layer(option_layer(timeout_layer)); /// # let _: Router = app; /// ``` /// /// # Difference between this and [`tower::util::option_layer`] /// /// `axum_extra::middleware::option_layer` makes sure that the output `Body` is [`axum::body::Body`]. /// /// [`Layer`]: tower_layer::Layer pub fn option_layer<L>(layer: Option<L>) -> Either<(ResponseAxumBodyLayer, L), Identity> { layer .map(|layer| Either::E1((ResponseAxumBodyLayer, layer))) .unwrap_or_else(|| Either::E2(Identity::new())) } #[cfg(test)] mod tests { use std::{ convert::Infallible, pin::Pin, task::{Context, Poll}, }; use axum::{body::Body as AxumBody, Router}; use bytes::Bytes; use http_body::Body as HttpBody; use tower_http::map_response_body::MapResponseBodyLayer; use super::option_layer; #[test] fn remap_response_body() { struct BodyWrapper; impl BodyWrapper { fn new(_: AxumBody) -> Self { Self } } impl HttpBody for BodyWrapper { type Data = Bytes; type Error = Infallible; fn poll_frame( self: Pin<&mut Self>, _cx: &mut Context<'_>, ) -> Poll<Option<Result<http_body::Frame<Self::Data>, Self::Error>>> { unimplemented!() } fn is_end_stream(&self) -> bool { unimplemented!() } fn size_hint(&self) -> http_body::SizeHint { unimplemented!() } } let _app: Router = Router::new().layer(option_layer(Some(MapResponseBodyLayer::new( BodyWrapper::new, )))); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/either.rs
axum-extra/src/either.rs
//! `Either*` types for combining extractors or responses into a single type. //! //! # As an extractor //! //! ``` //! use axum_extra::either::Either3; //! use axum::{ //! body::Bytes, //! Router, //! routing::get, //! extract::FromRequestParts, //! }; //! //! // extractors for checking permissions //! struct AdminPermissions {} //! //! impl<S> FromRequestParts<S> for AdminPermissions //! where //! S: Send + Sync, //! { //! // check for admin permissions... //! # type Rejection = (); //! # async fn from_request_parts(parts: &mut axum::http::request::Parts, state: &S) -> Result<Self, Self::Rejection> { //! # todo!() //! # } //! } //! //! struct User {} //! //! impl<S> FromRequestParts<S> for User //! where //! S: Send + Sync, //! { //! // check for a logged in user... //! # type Rejection = (); //! # async fn from_request_parts(parts: &mut axum::http::request::Parts, state: &S) -> Result<Self, Self::Rejection> { //! # todo!() //! # } //! } //! //! async fn handler( //! body: Either3<AdminPermissions, User, ()>, //! ) { //! match body { //! Either3::E1(admin) => { /* ... */ } //! Either3::E2(user) => { /* ... */ } //! Either3::E3(guest) => { /* ... */ } //! } //! } //! # //! # let _: axum::routing::MethodRouter = axum::routing::get(handler); //! ``` //! //! Note that if all the inner extractors reject the request, the rejection from the last //! extractor will be returned. For the example above that would be [`BytesRejection`]. //! //! # As a response //! //! ``` //! use axum_extra::either::Either3; //! use axum::{Json, http::StatusCode, response::IntoResponse}; //! use serde_json::{Value, json}; //! //! async fn handler() -> Either3<Json<Value>, &'static str, StatusCode> { //! if something() { //! Either3::E1(Json(json!({ "data": "..." }))) //! } else if something_else() { //! Either3::E2("foobar") //! } else { //! Either3::E3(StatusCode::NOT_FOUND) //! } //! } //! //! fn something() -> bool { //! // ... //! # false //! } //! //! fn something_else() -> bool { //! // ... //! # false //! } //! # //! # let _: axum::routing::MethodRouter = axum::routing::get(handler); //! ``` //! //! The general recommendation is to use [`IntoResponse::into_response`] to return different response //! types, but if you need to preserve the exact type then `Either*` works as well. //! //! [`BytesRejection`]: axum::extract::rejection::BytesRejection //! [`IntoResponse::into_response`]: https://docs.rs/axum/0.8/axum/response/index.html#returning-different-response-types use std::task::{Context, Poll}; use axum_core::{ extract::FromRequestParts, response::{IntoResponse, Response}, }; use http::request::Parts; use tower_layer::Layer; use tower_service::Service; /// Combines two extractors or responses into a single type. /// /// See the [module docs](self) for examples. #[derive(Debug, Clone)] #[must_use] pub enum Either<E1, E2> { #[allow(missing_docs)] E1(E1), #[allow(missing_docs)] E2(E2), } /// Combines three extractors or responses into a single type. /// /// See the [module docs](self) for examples. #[derive(Debug, Clone)] #[must_use] pub enum Either3<E1, E2, E3> { #[allow(missing_docs)] E1(E1), #[allow(missing_docs)] E2(E2), #[allow(missing_docs)] E3(E3), } /// Combines four extractors or responses into a single type. /// /// See the [module docs](self) for examples. #[derive(Debug, Clone)] #[must_use] pub enum Either4<E1, E2, E3, E4> { #[allow(missing_docs)] E1(E1), #[allow(missing_docs)] E2(E2), #[allow(missing_docs)] E3(E3), #[allow(missing_docs)] E4(E4), } /// Combines five extractors or responses into a single type. /// /// See the [module docs](self) for examples. #[derive(Debug, Clone)] #[must_use] pub enum Either5<E1, E2, E3, E4, E5> { #[allow(missing_docs)] E1(E1), #[allow(missing_docs)] E2(E2), #[allow(missing_docs)] E3(E3), #[allow(missing_docs)] E4(E4), #[allow(missing_docs)] E5(E5), } /// Combines six extractors or responses into a single type. /// /// See the [module docs](self) for examples. #[derive(Debug, Clone)] #[must_use] pub enum Either6<E1, E2, E3, E4, E5, E6> { #[allow(missing_docs)] E1(E1), #[allow(missing_docs)] E2(E2), #[allow(missing_docs)] E3(E3), #[allow(missing_docs)] E4(E4), #[allow(missing_docs)] E5(E5), #[allow(missing_docs)] E6(E6), } /// Combines seven extractors or responses into a single type. /// /// See the [module docs](self) for examples. #[derive(Debug, Clone)] #[must_use] pub enum Either7<E1, E2, E3, E4, E5, E6, E7> { #[allow(missing_docs)] E1(E1), #[allow(missing_docs)] E2(E2), #[allow(missing_docs)] E3(E3), #[allow(missing_docs)] E4(E4), #[allow(missing_docs)] E5(E5), #[allow(missing_docs)] E6(E6), #[allow(missing_docs)] E7(E7), } /// Combines eight extractors or responses into a single type. /// /// See the [module docs](self) for examples. #[derive(Debug, Clone)] #[must_use] pub enum Either8<E1, E2, E3, E4, E5, E6, E7, E8> { #[allow(missing_docs)] E1(E1), #[allow(missing_docs)] E2(E2), #[allow(missing_docs)] E3(E3), #[allow(missing_docs)] E4(E4), #[allow(missing_docs)] E5(E5), #[allow(missing_docs)] E6(E6), #[allow(missing_docs)] E7(E7), #[allow(missing_docs)] E8(E8), } macro_rules! impl_traits_for_either { ( $either:ident => [$($ident:ident),* $(,)?], $last:ident $(,)? ) => { impl<S, $($ident),*, $last> FromRequestParts<S> for $either<$($ident),*, $last> where $($ident: FromRequestParts<S>),*, $last: FromRequestParts<S>, S: Send + Sync, { type Rejection = $last::Rejection; async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { $( if let Ok(value) = <$ident as FromRequestParts<S>>::from_request_parts(parts, state).await { return Ok(Self::$ident(value)); } )* <$last as FromRequestParts<S>>::from_request_parts(parts, state).await.map(Self::$last) } } impl<$($ident),*, $last> IntoResponse for $either<$($ident),*, $last> where $($ident: IntoResponse),*, $last: IntoResponse, { fn into_response(self) -> Response { match self { $( Self::$ident(value) => value.into_response(), )* Self::$last(value) => value.into_response(), } } } }; } impl_traits_for_either!(Either => [E1], E2); impl_traits_for_either!(Either3 => [E1, E2], E3); impl_traits_for_either!(Either4 => [E1, E2, E3], E4); impl_traits_for_either!(Either5 => [E1, E2, E3, E4], E5); impl_traits_for_either!(Either6 => [E1, E2, E3, E4, E5], E6); impl_traits_for_either!(Either7 => [E1, E2, E3, E4, E5, E6], E7); impl_traits_for_either!(Either8 => [E1, E2, E3, E4, E5, E6, E7], E8); impl<E1, E2, S> Layer<S> for Either<E1, E2> where E1: Layer<S>, E2: Layer<S>, { type Service = Either<E1::Service, E2::Service>; fn layer(&self, inner: S) -> Self::Service { match self { Self::E1(layer) => Either::E1(layer.layer(inner)), Self::E2(layer) => Either::E2(layer.layer(inner)), } } } impl<R, E1, E2> Service<R> for Either<E1, E2> where E1: Service<R>, E2: Service<R, Response = E1::Response, Error = E1::Error>, { type Response = E1::Response; type Error = E1::Error; type Future = futures_util::future::Either<E1::Future, E2::Future>; fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { match self { Self::E1(inner) => inner.poll_ready(cx), Self::E2(inner) => inner.poll_ready(cx), } } fn call(&mut self, req: R) -> Self::Future { match self { Self::E1(inner) => futures_util::future::Either::Left(inner.call(req)), Self::E2(inner) => futures_util::future::Either::Right(inner.call(req)), } } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/json_lines.rs
axum-extra/src/json_lines.rs
//! Newline delimited JSON extractor and response. use axum_core::{ body::Body, extract::{FromRequest, Request}, response::{IntoResponse, Response}, BoxError, RequestExt, }; use bytes::{BufMut, BytesMut}; use futures_core::{stream::BoxStream, Stream, TryStream}; use futures_util::stream::TryStreamExt; use pin_project_lite::pin_project; use serde_core::{de::DeserializeOwned, Serialize}; use std::{ convert::Infallible, io::{self, Write}, marker::PhantomData, pin::Pin, task::{Context, Poll}, }; use tokio::io::AsyncBufReadExt; use tokio_stream::wrappers::LinesStream; use tokio_util::io::StreamReader; pin_project! { /// A stream of newline delimited JSON. /// /// This can be used both as an extractor and as a response. /// /// # As extractor /// /// ```rust /// use axum_extra::json_lines::JsonLines; /// use futures_util::stream::StreamExt; /// /// async fn handler(mut stream: JsonLines<serde_json::Value>) { /// while let Some(value) = stream.next().await { /// // ... /// } /// } /// ``` /// /// # As response /// /// ```rust /// use axum::{BoxError, response::{IntoResponse, Response}}; /// use axum_extra::json_lines::JsonLines; /// use futures_core::stream::Stream; /// /// fn stream_of_values() -> impl Stream<Item = Result<serde_json::Value, BoxError>> { /// # futures_util::stream::empty() /// } /// /// async fn handler() -> Response { /// JsonLines::new(stream_of_values()).into_response() /// } /// ``` // we use `AsExtractor` as the default because you're more likely to name this type if it's used // as an extractor #[must_use] pub struct JsonLines<S, T = AsExtractor> { #[pin] inner: Inner<S>, _marker: PhantomData<T>, } } pin_project! { #[project = InnerProj] enum Inner<S> { Response { #[pin] stream: S, }, Extractor { #[pin] stream: BoxStream<'static, Result<S, axum_core::Error>>, }, } } /// Marker type used to prove that an `JsonLines` was constructed via `FromRequest`. #[derive(Debug)] #[non_exhaustive] pub struct AsExtractor; /// Marker type used to prove that an `JsonLines` was constructed via `JsonLines::new`. #[derive(Debug)] #[non_exhaustive] pub struct AsResponse; impl<S> JsonLines<S, AsResponse> { /// Create a new `JsonLines` from a stream of items. pub fn new(stream: S) -> Self { Self { inner: Inner::Response { stream }, _marker: PhantomData, } } } impl<S, T> FromRequest<S> for JsonLines<T, AsExtractor> where T: DeserializeOwned, S: Send + Sync, { type Rejection = Infallible; async fn from_request(req: Request, _state: &S) -> Result<Self, Self::Rejection> { // `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 = req.into_limited_body(); let stream = body.into_data_stream(); let stream = stream.map_err(io::Error::other); let read = StreamReader::new(stream); let lines_stream = LinesStream::new(read.lines()); let deserialized_stream = lines_stream .map_err(axum_core::Error::new) .and_then(|value| async move { serde_json::from_str::<T>(&value).map_err(axum_core::Error::new) }); Ok(Self { inner: Inner::Extractor { stream: Box::pin(deserialized_stream), }, _marker: PhantomData, }) } } impl<T> Stream for JsonLines<T, AsExtractor> { type Item = Result<T, axum_core::Error>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { match self.project().inner.project() { InnerProj::Extractor { stream } => stream.poll_next(cx), // `JsonLines<_, AsExtractor>` can only be constructed via `FromRequest` // which doesn't use this variant InnerProj::Response { .. } => unreachable!(), } } } impl<S> IntoResponse for JsonLines<S, AsResponse> where S: TryStream + Send + 'static, S::Ok: Serialize + Send, S::Error: Into<BoxError>, { fn into_response(self) -> Response { let inner = match self.inner { Inner::Response { stream } => stream, // `JsonLines<_, AsResponse>` can only be constructed via `JsonLines::new` // which doesn't use this variant Inner::Extractor { .. } => unreachable!(), }; let stream = inner.map_err(Into::into).and_then(|value| async move { let mut buf = BytesMut::new().writer(); serde_json::to_writer(&mut buf, &value)?; buf.write_all(b"\n")?; Ok::<_, BoxError>(buf.into_inner().freeze()) }); let stream = Body::from_stream(stream); // there is no consensus around mime type yet // https://github.com/wardi/jsonlines/issues/36 stream.into_response() } } #[cfg(test)] mod tests { use super::JsonLines; use crate::test_helpers::*; use axum::{ routing::{get, post}, Router, }; use futures_util::StreamExt; use http::StatusCode; use serde::{Deserialize, Serialize}; use std::{convert::Infallible, error::Error}; #[derive(Serialize, Deserialize, PartialEq, Eq, Debug)] struct User { id: i32, } #[tokio::test] async fn extractor() { let app = Router::new().route( "/", post(|mut stream: JsonLines<User>| async move { assert_eq!(stream.next().await.unwrap().unwrap(), User { id: 1 }); assert_eq!(stream.next().await.unwrap().unwrap(), User { id: 2 }); assert_eq!(stream.next().await.unwrap().unwrap(), User { id: 3 }); // sources are downcastable to `serde_json::Error` let err = stream.next().await.unwrap().unwrap_err(); let _: &serde_json::Error = err .source() .unwrap() .downcast_ref::<serde_json::Error>() .unwrap(); }), ); let client = TestClient::new(app); let res = client .post("/") .body( [ "{\"id\":1}", "{\"id\":2}", "{\"id\":3}", // to trigger an error for source downcasting "{\"id\":false}", ] .join("\n"), ) .await; assert_eq!(res.status(), StatusCode::OK); } #[tokio::test] async fn response() { let app = Router::new().route( "/", get(|| async { let values = futures_util::stream::iter(vec![ Ok::<_, Infallible>(User { id: 1 }), Ok::<_, Infallible>(User { id: 2 }), Ok::<_, Infallible>(User { id: 3 }), ]); JsonLines::new(values) }), ); let client = TestClient::new(app); let res = client.get("/").await; let values = res .text() .await .lines() .map(|line| serde_json::from_str::<User>(line).unwrap()) .collect::<Vec<_>>(); assert_eq!( values, vec![User { id: 1 }, User { id: 2 }, User { id: 3 },] ); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/typed_header.rs
axum-extra/src/typed_header.rs
//! Extractor and response for typed headers. use axum_core::{ extract::{FromRequestParts, OptionalFromRequestParts}, response::{IntoResponse, IntoResponseParts, Response, ResponseParts}, }; use headers::{Header, HeaderMapExt}; use http::{request::Parts, StatusCode}; use std::convert::Infallible; /// Extractor and response that works with typed header values from [`headers`]. /// /// # As extractor /// /// In general, it's recommended to extract only the needed headers via `TypedHeader` rather than /// removing all headers with the `HeaderMap` extractor. /// /// ```rust,no_run /// use axum::{ /// routing::get, /// Router, /// }; /// use headers::UserAgent; /// use axum_extra::TypedHeader; /// /// async fn users_teams_show( /// TypedHeader(user_agent): TypedHeader<UserAgent>, /// ) { /// // ... /// } /// /// let app = Router::new().route("/users/{user_id}/team/{team_id}", get(users_teams_show)); /// # let _: Router = app; /// ``` /// /// # As response /// /// ```rust /// use axum::{ /// response::IntoResponse, /// }; /// use headers::ContentType; /// use axum_extra::TypedHeader; /// /// async fn handler() -> (TypedHeader<ContentType>, &'static str) { /// ( /// TypedHeader(ContentType::text_utf8()), /// "Hello, World!", /// ) /// } /// ``` #[cfg(feature = "typed-header")] #[derive(Debug, Clone, Copy)] #[must_use] pub struct TypedHeader<T>(pub T); impl<T, S> FromRequestParts<S> for TypedHeader<T> where T: Header, S: Send + Sync, { type Rejection = TypedHeaderRejection; async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> { let mut values = parts.headers.get_all(T::name()).iter(); let is_missing = values.size_hint() == (0, Some(0)); T::decode(&mut values) .map(Self) .map_err(|err| TypedHeaderRejection { name: T::name(), reason: if is_missing { // Report a more precise rejection for the missing header case. TypedHeaderRejectionReason::Missing } else { TypedHeaderRejectionReason::Error(err) }, }) } } impl<T, S> OptionalFromRequestParts<S> for TypedHeader<T> where T: Header, S: Send + Sync, { type Rejection = TypedHeaderRejection; async fn from_request_parts( parts: &mut Parts, _state: &S, ) -> Result<Option<Self>, Self::Rejection> { let mut values = parts.headers.get_all(T::name()).iter(); let is_missing = values.size_hint() == (0, Some(0)); match T::decode(&mut values) { Ok(res) => Ok(Some(Self(res))), Err(_) if is_missing => Ok(None), Err(err) => Err(TypedHeaderRejection { name: T::name(), reason: TypedHeaderRejectionReason::Error(err), }), } } } axum_core::__impl_deref!(TypedHeader); impl<T> IntoResponseParts for TypedHeader<T> where T: Header, { type Error = Infallible; fn into_response_parts(self, mut res: ResponseParts) -> Result<ResponseParts, Self::Error> { res.headers_mut().typed_insert(self.0); Ok(res) } } impl<T> IntoResponse for TypedHeader<T> where T: Header, { fn into_response(self) -> Response { let mut res = ().into_response(); res.headers_mut().typed_insert(self.0); res } } /// Rejection used for [`TypedHeader`]. #[cfg(feature = "typed-header")] #[derive(Debug)] pub struct TypedHeaderRejection { name: &'static http::header::HeaderName, reason: TypedHeaderRejectionReason, } impl TypedHeaderRejection { /// Name of the header that caused the rejection #[must_use] pub fn name(&self) -> &http::header::HeaderName { self.name } /// Reason why the header extraction has failed #[must_use] pub fn reason(&self) -> &TypedHeaderRejectionReason { &self.reason } /// Returns `true` if the typed header rejection reason is [`Missing`]. /// /// [`Missing`]: TypedHeaderRejectionReason::Missing #[must_use] pub fn is_missing(&self) -> bool { self.reason.is_missing() } } /// Additional information regarding a [`TypedHeaderRejection`] #[cfg(feature = "typed-header")] #[derive(Debug)] #[non_exhaustive] pub enum TypedHeaderRejectionReason { /// The header was missing from the HTTP request Missing, /// An error occurred when parsing the header from the HTTP request Error(headers::Error), } impl TypedHeaderRejectionReason { /// Returns `true` if the typed header rejection reason is [`Missing`]. /// /// [`Missing`]: TypedHeaderRejectionReason::Missing #[must_use] pub fn is_missing(&self) -> bool { matches!(self, Self::Missing) } } impl IntoResponse for TypedHeaderRejection { fn into_response(self) -> Response { let status = StatusCode::BAD_REQUEST; let body = self.to_string(); axum_core::__log_rejection!(rejection_type = Self, body_text = body, status = status,); (status, body).into_response() } } impl std::fmt::Display for TypedHeaderRejection { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self.reason { TypedHeaderRejectionReason::Missing => { write!(f, "Header of type `{}` was missing", self.name) } TypedHeaderRejectionReason::Error(err) => { write!(f, "{err} ({})", self.name) } } } } impl std::error::Error for TypedHeaderRejection { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { match &self.reason { TypedHeaderRejectionReason::Error(err) => Some(err), TypedHeaderRejectionReason::Missing => None, } } } #[cfg(test)] mod tests { use super::*; use crate::test_helpers::*; use axum::{routing::get, Router}; #[tokio::test] async fn typed_header() { async fn handle( TypedHeader(user_agent): TypedHeader<headers::UserAgent>, TypedHeader(cookies): TypedHeader<headers::Cookie>, ) -> impl IntoResponse { let user_agent = user_agent.as_str(); let cookies = cookies.iter().collect::<Vec<_>>(); format!("User-Agent={user_agent:?}, Cookie={cookies:?}") } let app = Router::new().route("/", get(handle)); let client = TestClient::new(app); let res = client .get("/") .header("user-agent", "foobar") .header("cookie", "a=1; b=2") .header("cookie", "c=3") .await; let body = res.text().await; assert_eq!( body, r#"User-Agent="foobar", Cookie=[("a", "1"), ("b", "2"), ("c", "3")]"# ); let res = client.get("/").header("user-agent", "foobar").await; let body = res.text().await; assert_eq!(body, r#"User-Agent="foobar", Cookie=[]"#); let res = client.get("/").header("cookie", "a=1").await; let body = res.text().await; assert_eq!(body, "Header of type `user-agent` was missing"); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/protobuf.rs
axum-extra/src/protobuf.rs
//! Protocol Buffer extractor and response. use axum_core::__composite_rejection as composite_rejection; use axum_core::__define_rejection as define_rejection; use axum_core::{ extract::{rejection::BytesRejection, FromRequest, Request}, response::{IntoResponse, Response}, RequestExt, }; use bytes::BytesMut; use http::StatusCode; use http_body_util::BodyExt; use prost::Message; /// A Protocol Buffer message extractor and response. /// /// This can be used both as an extractor and as a response. /// /// # As extractor /// /// When used as an extractor, it can decode request bodies into some type that /// implements [`prost::Message`]. The request will be rejected (and a [`ProtobufRejection`] will /// be returned) if: /// /// - The body couldn't be decoded into the target Protocol Buffer message type. /// - Buffering the request body fails. /// /// See [`ProtobufRejection`] for more details. /// /// The extractor does not expect a `Content-Type` header to be present in the request. /// /// # Extractor example /// /// ```rust,no_run /// use axum::{routing::post, Router}; /// use axum_extra::protobuf::Protobuf; /// /// #[derive(prost::Message)] /// struct CreateUser { /// #[prost(string, tag="1")] /// email: String, /// #[prost(string, tag="2")] /// password: String, /// } /// /// async fn create_user(Protobuf(payload): Protobuf<CreateUser>) { /// // payload is `CreateUser` /// } /// /// let app = Router::new().route("/users", post(create_user)); /// # let _: Router = app; /// ``` /// /// # As response /// /// When used as a response, it can encode any type that implements [`prost::Message`] to /// a newly allocated buffer. /// /// If no `Content-Type` header is set, the `Content-Type: application/octet-stream` header /// will be used automatically. /// /// # Response example /// /// ``` /// use axum::{ /// extract::Path, /// routing::get, /// Router, /// }; /// use axum_extra::protobuf::Protobuf; /// /// #[derive(prost::Message)] /// struct User { /// #[prost(string, tag="1")] /// username: String, /// } /// /// async fn get_user(Path(user_id) : Path<String>) -> Protobuf<User> { /// let user = find_user(user_id).await; /// Protobuf(user) /// } /// /// async fn find_user(user_id: String) -> User { /// // ... /// # unimplemented!() /// } /// /// let app = Router::new().route("/users/{id}", get(get_user)); /// # let _: Router = app; /// ``` #[derive(Debug, Clone, Copy, Default)] #[cfg_attr(docsrs, doc(cfg(feature = "protobuf")))] #[must_use] pub struct Protobuf<T>(pub T); impl<T, S> FromRequest<S> for Protobuf<T> where T: Message + Default, S: Send + Sync, { type Rejection = ProtobufRejection; async fn from_request(req: Request, _: &S) -> Result<Self, Self::Rejection> { let mut buf = req .into_limited_body() .collect() .await .map_err(ProtobufDecodeError)? .aggregate(); match T::decode(&mut buf) { Ok(value) => Ok(Self(value)), Err(err) => Err(ProtobufDecodeError::from_err(err).into()), } } } axum_core::__impl_deref!(Protobuf); impl<T> From<T> for Protobuf<T> { fn from(inner: T) -> Self { Self(inner) } } impl<T> IntoResponse for Protobuf<T> where T: Message + Default, { fn into_response(self) -> Response { let mut buf = BytesMut::with_capacity(self.0.encoded_len()); match &self.0.encode(&mut buf) { Ok(()) => buf.into_response(), Err(err) => (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()).into_response(), } } } define_rejection! { #[status = UNPROCESSABLE_ENTITY] #[body = "Failed to decode the body"] /// Rejection type for [`Protobuf`]. /// /// This rejection is used if the request body couldn't be decoded into the target type. pub struct ProtobufDecodeError(Error); } composite_rejection! { /// Rejection used for [`Protobuf`]. /// /// Contains one variant for each way the [`Protobuf`] extractor /// can fail. pub enum ProtobufRejection { ProtobufDecodeError, BytesRejection, } } #[cfg(test)] mod tests { use super::*; use crate::test_helpers::*; use axum::{routing::post, Router}; use http::header::CONTENT_TYPE; use http::StatusCode; #[tokio::test] async fn decode_body() { #[derive(prost::Message)] struct Input { #[prost(string, tag = "1")] foo: String, } let app = Router::new().route( "/", post(|Protobuf(input): Protobuf<Input>| async move { input.foo }), ); let input = Input { foo: "bar".to_owned(), }; let client = TestClient::new(app); let res = client.post("/").body(input.encode_to_vec()).await; let status = res.status(); let body = res.text().await; assert_eq!(status, StatusCode::OK); assert_eq!(body, input.foo); } #[tokio::test] async fn prost_decode_error() { #[derive(prost::Message)] struct Input { #[prost(string, tag = "1")] foo: String, } #[derive(prost::Message)] struct Expected { #[prost(int32, tag = "1")] test: i32, } let app = Router::new().route("/", post(|_: Protobuf<Expected>| async {})); let input = Input { foo: "bar".to_owned(), }; let client = TestClient::new(app); let res = client.post("/").body(input.encode_to_vec()).await; assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY); assert!(res.text().await.starts_with("Failed to decode the body")); } #[tokio::test] async fn encode_body() { #[derive(prost::Message)] struct Input { #[prost(string, tag = "1")] foo: String, } #[derive(prost::Message)] struct Output { #[prost(string, tag = "1")] result: String, } #[axum::debug_handler] async fn handler(Protobuf(input): Protobuf<Input>) -> Protobuf<Output> { let output = Output { result: input.foo }; Protobuf(output) } let app = Router::new().route("/", post(handler)); let input = Input { foo: "bar".to_owned(), }; let client = TestClient::new(app); let res = client.post("/").body(input.encode_to_vec()).await; let content_type_header_value = res .headers() .get(CONTENT_TYPE) .expect("missing expected header"); assert_eq!( content_type_header_value, mime::APPLICATION_OCTET_STREAM.as_ref() ); let body = res.bytes().await; let output = Output::decode(body).unwrap(); assert_eq!(output.result, input.foo); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/extract/cached.rs
axum-extra/src/extract/cached.rs
use axum::extract::FromRequestParts; use http::request::Parts; /// Cache results of other extractors. /// /// `Cached` wraps another extractor and caches its result in [request extensions]. /// /// This is useful if you have a tree of extractors that share common sub-extractors that /// you only want to run once, perhaps because they're expensive. /// /// The cache purely type based so you can only cache one value of each type. The cache is also /// local to the current request and not reused across requests. /// /// # Example /// /// ```rust /// use axum_extra::extract::Cached; /// use axum::{ /// extract::FromRequestParts, /// response::{IntoResponse, Response}, /// http::{StatusCode, request::Parts}, /// }; /// /// #[derive(Clone)] /// struct Session { /* ... */ } /// /// impl<S> FromRequestParts<S> for Session /// where /// S: Send + Sync, /// { /// type Rejection = (StatusCode, String); /// /// async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { /// // load session... /// # unimplemented!() /// } /// } /// /// struct CurrentUser { /* ... */ } /// /// impl<S> FromRequestParts<S> for CurrentUser /// where /// S: Send + Sync, /// { /// type Rejection = Response; /// /// async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { /// // loading a `CurrentUser` requires first loading the `Session` /// // /// // by using `Cached<Session>` we avoid extracting the session more than /// // once, in case other extractors for the same request also loads the session /// let session: Session = Cached::<Session>::from_request_parts(parts, state) /// .await /// .map_err(|err| err.into_response())? /// .0; /// /// // load user from session... /// # unimplemented!() /// } /// } /// /// // handler that extracts the current user and the session /// // /// // the session will only be loaded once, even though `CurrentUser` /// // also loads it /// async fn handler( /// current_user: CurrentUser, /// // we have to use `Cached<Session>` here otherwise the /// // cached session would not be used /// Cached(session): Cached<Session>, /// ) { /// // ... /// } /// ``` /// /// [request extensions]: http::Extensions #[derive(Debug, Clone, Default)] pub struct Cached<T>(pub T); #[derive(Clone)] struct CachedEntry<T>(T); impl<S, T> FromRequestParts<S> for Cached<T> where S: Send + Sync, T: FromRequestParts<S> + Clone + Send + Sync + 'static, { type Rejection = T::Rejection; async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { if let Some(value) = parts.extensions.get::<CachedEntry<T>>() { Ok(Self(value.0.clone())) } else { let value = T::from_request_parts(parts, state).await?; parts.extensions.insert(CachedEntry(value.clone())); Ok(Self(value)) } } } axum_core::__impl_deref!(Cached); #[cfg(test)] mod tests { use super::*; use axum::{http::Request, routing::get, Router}; use std::{ convert::Infallible, sync::atomic::{AtomicU32, Ordering}, time::Instant, }; #[tokio::test] async fn works() { static COUNTER: AtomicU32 = AtomicU32::new(0); #[derive(Clone, Debug, PartialEq, Eq)] struct Extractor(Instant); impl<S> FromRequestParts<S> for Extractor where S: Send + Sync, { type Rejection = Infallible; async fn from_request_parts( _parts: &mut Parts, _state: &S, ) -> Result<Self, Self::Rejection> { COUNTER.fetch_add(1, Ordering::SeqCst); Ok(Self(Instant::now())) } } let (mut parts, _) = Request::new(()).into_parts(); let first = Cached::<Extractor>::from_request_parts(&mut parts, &()) .await .unwrap() .0; assert_eq!(COUNTER.load(Ordering::SeqCst), 1); let second = Cached::<Extractor>::from_request_parts(&mut parts, &()) .await .unwrap() .0; assert_eq!(COUNTER.load(Ordering::SeqCst), 1); assert_eq!(first, second); } // Not a #[test], we just want to know this compiles async fn _last_handler_argument() { async fn handler(_: http::Method, _: Cached<http::HeaderMap>) {} let _r: Router = Router::new().route("/", get(handler)); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/extract/with_rejection.rs
axum-extra/src/extract/with_rejection.rs
use axum::extract::{FromRequest, FromRequestParts, Request}; use axum::response::IntoResponse; use http::request::Parts; use std::fmt::{Debug, Display}; use std::marker::PhantomData; use std::ops::{Deref, DerefMut}; #[cfg(feature = "typed-routing")] use crate::routing::TypedPath; /// Extractor for customizing extractor rejections /// /// `WithRejection` wraps another extractor and gives you the result. If the /// extraction fails, the `Rejection` is transformed into `R` and returned as a /// response /// /// `E` is expected to implement [`FromRequest`] /// /// `R` is expected to implement [`IntoResponse`] and [`From<E::Rejection>`] /// /// /// # Example /// /// ```rust /// use axum::extract::rejection::JsonRejection; /// use axum::response::{Response, IntoResponse}; /// use axum::Json; /// use axum_extra::extract::WithRejection; /// use serde::Deserialize; /// /// struct MyRejection { /* ... */ } /// /// impl From<JsonRejection> for MyRejection { /// fn from(rejection: JsonRejection) -> MyRejection { /// // ... /// # todo!() /// } /// } /// /// impl IntoResponse for MyRejection { /// fn into_response(self) -> Response { /// // ... /// # todo!() /// } /// } /// #[derive(Debug, Deserialize)] /// struct Person { /* ... */ } /// /// async fn handler( /// // If the `Json` extractor ever fails, `MyRejection` will be sent to the /// // client using the `IntoResponse` impl /// WithRejection(Json(Person), _): WithRejection<Json<Person>, MyRejection> /// ) { /* ... */ } /// # let _: axum::Router = axum::Router::new().route("/", axum::routing::get(handler)); /// ``` /// /// [`FromRequest`]: axum::extract::FromRequest /// [`IntoResponse`]: axum::response::IntoResponse /// [`From<E::Rejection>`]: std::convert::From pub struct WithRejection<E, R>(pub E, pub PhantomData<R>); impl<E, R> WithRejection<E, R> { /// Returns the wrapped extractor pub fn into_inner(self) -> E { self.0 } } impl<E, R> Debug for WithRejection<E, R> where E: Debug, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_tuple("WithRejection") .field(&self.0) .field(&self.1) .finish() } } impl<E, R> Clone for WithRejection<E, R> where E: Clone, { fn clone(&self) -> Self { Self(self.0.clone(), self.1) } } impl<E, R> Copy for WithRejection<E, R> where E: Copy {} impl<E: Default, R> Default for WithRejection<E, R> { fn default() -> Self { Self(Default::default(), Default::default()) } } impl<E, R> Deref for WithRejection<E, R> { type Target = E; fn deref(&self) -> &Self::Target { &self.0 } } impl<E, R> DerefMut for WithRejection<E, R> { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } impl<E, R, S> FromRequest<S> for WithRejection<E, R> where S: Send + Sync, E: FromRequest<S>, R: From<E::Rejection> + IntoResponse, { type Rejection = R; async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> { let extractor = E::from_request(req, state).await?; Ok(Self(extractor, PhantomData)) } } impl<E, R, S> FromRequestParts<S> for WithRejection<E, R> where S: Send + Sync, E: FromRequestParts<S>, R: From<E::Rejection> + IntoResponse, { type Rejection = R; async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { let extractor = E::from_request_parts(parts, state).await?; Ok(Self(extractor, PhantomData)) } } #[cfg(feature = "typed-routing")] impl<E, R> TypedPath for WithRejection<E, R> where E: TypedPath, { const PATH: &'static str = E::PATH; } impl<E, R> Display for WithRejection<E, R> where E: Display, { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.0) } } #[cfg(test)] mod tests { use super::*; use axum::body::Body; use axum::http::Request; use axum::response::Response; #[tokio::test] async fn extractor_rejection_is_transformed() { struct TestExtractor; struct TestRejection; impl<S> FromRequestParts<S> for TestExtractor where S: Send + Sync, { type Rejection = (); async fn from_request_parts( _parts: &mut Parts, _state: &S, ) -> Result<Self, Self::Rejection> { Err(()) } } impl IntoResponse for TestRejection { fn into_response(self) -> Response { ().into_response() } } impl From<()> for TestRejection { fn from(_: ()) -> Self { Self } } let req = Request::new(Body::empty()); let result = WithRejection::<TestExtractor, TestRejection>::from_request(req, &()).await; assert!(matches!(result, Err(TestRejection))); let (mut parts, _) = Request::new(()).into_parts(); let result = WithRejection::<TestExtractor, TestRejection>::from_request_parts(&mut parts, &()) .await; assert!(matches!(result, Err(TestRejection))); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/extract/multipart.rs
axum-extra/src/extract/multipart.rs
//! Extractor that parses `multipart/form-data` requests commonly used with file uploads. //! //! See [`Multipart`] for more details. use axum_core::{ RequestExt, __composite_rejection as composite_rejection, __define_rejection as define_rejection, body::Body, extract::FromRequest, response::{IntoResponse, Response}, }; use bytes::Bytes; use futures_core::stream::Stream; use http::{ header::{HeaderMap, CONTENT_TYPE}, Request, StatusCode, }; use std::{ error::Error, fmt, pin::Pin, task::{Context, Poll}, }; /// Extractor that parses `multipart/form-data` requests (commonly used with file uploads). /// /// ⚠️ Since extracting multipart form data from the request requires consuming the body, the /// `Multipart` 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 /// /// ``` /// use axum::{ /// routing::post, /// Router, /// }; /// use axum_extra::extract::Multipart; /// /// async fn upload(mut multipart: Multipart) { /// while let Some(mut field) = multipart.next_field().await.unwrap() { /// let name = field.name().unwrap().to_string(); /// let data = field.bytes().await.unwrap(); /// /// println!("Length of `{}` is {} bytes", name, data.len()); /// } /// } /// /// let app = Router::new().route("/upload", post(upload)); /// # let _: Router = app; /// ``` /// /// # Field Exclusivity /// /// A [`Field`] represents a raw, self-decoding stream into multipart data. As such, only one /// [`Field`] from a given Multipart instance may be live at once. That is, a [`Field`] emitted by /// [`next_field()`] must be dropped before calling [`next_field()`] again. Failure to do so will /// result in an error. /// /// ``` /// use axum_extra::extract::Multipart; /// /// async fn handler(mut multipart: Multipart) { /// let field_1 = multipart.next_field().await; /// /// // We cannot get the next field while `field_1` is still alive. Have to drop `field_1` /// // first. /// let field_2 = multipart.next_field().await; /// assert!(field_2.is_err()); /// } /// ``` /// /// In general you should consume `Multipart` by looping over the fields in order and make sure not /// to keep `Field`s around from previous loop iterations. That will minimize the risk of runtime /// errors. /// /// # Differences between this and `axum::extract::Multipart` /// /// `axum::extract::Multipart` uses lifetimes to enforce field exclusivity at compile time, however /// that leads to significant usability issues such as `Field` not being `'static`. /// /// `axum_extra::extract::Multipart` instead enforces field exclusivity at runtime which makes /// things easier to use at the cost of possible runtime errors. /// /// [`next_field()`]: Multipart::next_field #[cfg_attr(docsrs, doc(cfg(feature = "multipart")))] #[derive(Debug)] pub struct Multipart { inner: multer::Multipart<'static>, } impl<S> FromRequest<S> for Multipart where S: Send + Sync, { type Rejection = MultipartRejection; async fn from_request(req: Request<Body>, _state: &S) -> Result<Self, Self::Rejection> { let boundary = parse_boundary(req.headers()).ok_or(InvalidBoundary)?; let stream = req.with_limited_body().into_body(); let multipart = multer::Multipart::new(stream.into_data_stream(), boundary); Ok(Self { inner: multipart }) } } impl Multipart { /// Yields the next [`Field`] if available. pub async fn next_field(&mut self) -> Result<Option<Field>, MultipartError> { let field = self .inner .next_field() .await .map_err(MultipartError::from_multer)?; if let Some(field) = field { Ok(Some(Field { inner: field })) } else { Ok(None) } } /// Convert the `Multipart` into a stream of its fields. pub fn into_stream(self) -> impl Stream<Item = Result<Field, MultipartError>> + Send + 'static { futures_util::stream::try_unfold(self, |mut multipart| async move { let field = multipart.next_field().await?; Ok(field.map(|field| (field, multipart))) }) } } /// A single field in a multipart stream. #[derive(Debug)] pub struct Field { inner: multer::Field<'static>, } impl Stream for Field { type Item = Result<Bytes, MultipartError>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { Pin::new(&mut self.inner) .poll_next(cx) .map_err(MultipartError::from_multer) } } impl Field { /// The field name found in the /// [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) /// header. #[must_use] pub fn name(&self) -> Option<&str> { self.inner.name() } /// The file name found in the /// [`Content-Disposition`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition) /// header. #[must_use] pub fn file_name(&self) -> Option<&str> { self.inner.file_name() } /// Get the [content type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Type) of the field. #[must_use] pub fn content_type(&self) -> Option<&str> { self.inner.content_type().map(|m| m.as_ref()) } /// Get a map of headers as [`HeaderMap`]. #[must_use] pub fn headers(&self) -> &HeaderMap { self.inner.headers() } /// Get the full data of the field as [`Bytes`]. pub async fn bytes(self) -> Result<Bytes, MultipartError> { self.inner .bytes() .await .map_err(MultipartError::from_multer) } /// Get the full field data as text. pub async fn text(self) -> Result<String, MultipartError> { self.inner.text().await.map_err(MultipartError::from_multer) } /// Stream a chunk of the field data. /// /// When the field data has been exhausted, this will return [`None`]. /// /// Note this does the same thing as `Field`'s [`Stream`] implementation. /// /// # Example /// /// ``` /// use axum::{ /// routing::post, /// response::IntoResponse, /// http::StatusCode, /// Router, /// }; /// use axum_extra::extract::Multipart; /// /// async fn upload(mut multipart: Multipart) -> Result<(), (StatusCode, String)> { /// while let Some(mut field) = multipart /// .next_field() /// .await /// .map_err(|err| (StatusCode::BAD_REQUEST, err.to_string()))? /// { /// while let Some(chunk) = field /// .chunk() /// .await /// .map_err(|err| (StatusCode::BAD_REQUEST, err.to_string()))? /// { /// println!("received {} bytes", chunk.len()); /// } /// } /// /// Ok(()) /// } /// /// let app = Router::new().route("/upload", post(upload)); /// # let _: Router = app; /// ``` pub async fn chunk(&mut self) -> Result<Option<Bytes>, MultipartError> { self.inner .chunk() .await .map_err(MultipartError::from_multer) } } /// Errors associated with parsing `multipart/form-data` requests. #[derive(Debug)] pub struct MultipartError { source: multer::Error, } impl MultipartError { fn from_multer(multer: multer::Error) -> Self { Self { source: multer } } /// Get the response body text used for this rejection. pub fn body_text(&self) -> String { let body = self.source.to_string(); axum_core::__log_rejection!( rejection_type = Self, body_text = body, status = self.status(), ); body } /// Get the status code used for this rejection. #[must_use] pub fn status(&self) -> http::StatusCode { status_code_from_multer_error(&self.source) } } fn status_code_from_multer_error(err: &multer::Error) -> StatusCode { match err { multer::Error::UnknownField { .. } | multer::Error::IncompleteFieldData { .. } | multer::Error::IncompleteHeaders | multer::Error::ReadHeaderFailed(..) | multer::Error::DecodeHeaderName { .. } | multer::Error::DecodeContentType(..) | multer::Error::NoBoundary | multer::Error::DecodeHeaderValue { .. } | multer::Error::NoMultipart | multer::Error::IncompleteStream => StatusCode::BAD_REQUEST, multer::Error::FieldSizeExceeded { .. } | multer::Error::StreamSizeExceeded { .. } => { StatusCode::PAYLOAD_TOO_LARGE } multer::Error::StreamReadFailed(err) => { if let Some(err) = err.downcast_ref::<multer::Error>() { return status_code_from_multer_error(err); } if err .downcast_ref::<axum_core::Error>() .and_then(|err| err.source()) .and_then(|err| err.downcast_ref::<http_body_util::LengthLimitError>()) .is_some() { return StatusCode::PAYLOAD_TOO_LARGE; } StatusCode::INTERNAL_SERVER_ERROR } _ => StatusCode::INTERNAL_SERVER_ERROR, } } impl IntoResponse for MultipartError { fn into_response(self) -> Response { (self.status(), self.body_text()).into_response() } } impl fmt::Display for MultipartError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "Error parsing `multipart/form-data` request") } } impl std::error::Error for MultipartError { fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { Some(&self.source) } } fn parse_boundary(headers: &HeaderMap) -> Option<String> { let content_type = headers.get(CONTENT_TYPE)?.to_str().ok()?; multer::parse_boundary(content_type).ok() } composite_rejection! { /// Rejection used for [`Multipart`]. /// /// Contains one variant for each way the [`Multipart`] extractor can fail. pub enum MultipartRejection { InvalidBoundary, } } define_rejection! { #[status = BAD_REQUEST] #[body = "Invalid `boundary` for `multipart/form-data` request"] /// Rejection type used if the `boundary` in a `multipart/form-data` is /// missing or invalid. pub struct InvalidBoundary; } #[cfg(test)] mod tests { use super::*; use crate::test_helpers::*; use axum::{extract::DefaultBodyLimit, routing::post, Router}; #[tokio::test] async fn content_type_with_encoding() { const BYTES: &[u8] = "<!doctype html><title>🦀</title>".as_bytes(); const FILE_NAME: &str = "index.html"; const CONTENT_TYPE: &str = "text/html; charset=utf-8"; async fn handle(mut multipart: Multipart) -> impl IntoResponse { let field = multipart.next_field().await.unwrap().unwrap(); assert_eq!(field.file_name().unwrap(), FILE_NAME); assert_eq!(field.content_type().unwrap(), CONTENT_TYPE); assert_eq!(field.bytes().await.unwrap(), BYTES); assert!(multipart.next_field().await.unwrap().is_none()); } let app = Router::new().route("/", post(handle)); let client = TestClient::new(app); let form = reqwest::multipart::Form::new().part( "file", reqwest::multipart::Part::bytes(BYTES) .file_name(FILE_NAME) .mime_str(CONTENT_TYPE) .unwrap(), ); client.post("/").multipart(form).await; } // 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<()> = Router::new().route("/", post(handler)); } #[tokio::test] async fn body_too_large() { const BYTES: &[u8] = "<!doctype html><title>🦀</title>".as_bytes(); async fn handle(mut multipart: Multipart) -> Result<(), MultipartError> { while let Some(field) = multipart.next_field().await? { field.bytes().await?; } Ok(()) } let app = Router::new() .route("/", post(handle)) .layer(DefaultBodyLimit::max(BYTES.len() - 1)); let client = TestClient::new(app); let form = reqwest::multipart::Form::new().part("file", reqwest::multipart::Part::bytes(BYTES)); let res = client.post("/").multipart(form).await; assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE); } #[tokio::test] #[cfg(feature = "tracing")] async fn body_too_large_with_tracing() { const BYTES: &[u8] = "<!doctype html><title>🦀</title>".as_bytes(); async fn handle(mut multipart: Multipart) -> impl IntoResponse { let result: Result<(), MultipartError> = async { while let Some(field) = multipart.next_field().await? { field.bytes().await?; } Ok(()) } .await; let subscriber = tracing_subscriber::FmtSubscriber::builder() .with_max_level(tracing::level_filters::LevelFilter::TRACE) .with_writer(std::io::sink) .finish(); let guard = tracing::subscriber::set_default(subscriber); let response = result.into_response(); drop(guard); response } let app = Router::new() .route("/", post(handle)) .layer(DefaultBodyLimit::max(BYTES.len() - 1)); let client = TestClient::new(app); let form = reqwest::multipart::Form::new().part("file", reqwest::multipart::Part::bytes(BYTES)); let res = client.post("/").multipart(form).await; assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/extract/form.rs
axum-extra/src/extract/form.rs
#![allow(deprecated)] use axum::extract::rejection::RawFormRejection; use axum::{ extract::{FromRequest, RawForm, Request}, RequestExt, }; use axum_core::__composite_rejection as composite_rejection; use axum_core::__define_rejection as define_rejection; use serde_core::de::DeserializeOwned; /// Extractor that deserializes `application/x-www-form-urlencoded` requests /// into some type. /// /// `T` is expected to implement [`serde::Deserialize`]. /// /// # Deprecated /// /// This extractor used to use a different deserializer under-the-hood but that /// is no longer the case. Now it only uses an older version of the same /// deserializer, purely for ease of transition to the latest version. /// Before switching to `axum::extract::Form`, it is recommended to read the /// [changelog for `serde_html_form v0.3.0`][changelog]. /// /// [changelog]: https://github.com/jplatte/serde_html_form/blob/main/CHANGELOG.md#030 #[deprecated = "see documentation"] #[derive(Debug, Clone, Copy, Default)] #[cfg(feature = "form")] pub struct Form<T>(pub T); axum_core::__impl_deref!(Form); impl<T, S> FromRequest<S> for Form<T> where T: DeserializeOwned, S: Send + Sync, { type Rejection = FormRejection; async fn from_request(req: Request, _state: &S) -> Result<Self, Self::Rejection> { let is_get_or_head = req.method() == http::Method::GET || req.method() == http::Method::HEAD; let RawForm(bytes) = req.extract().await?; let deserializer = serde_html_form::Deserializer::new(form_urlencoded::parse(&bytes)); serde_path_to_error::deserialize::<_, T>(deserializer) .map(Self) .map_err(|err| { if is_get_or_head { FailedToDeserializeForm::from_err(err).into() } else { FailedToDeserializeFormBody::from_err(err).into() } }) } } define_rejection! { #[status = BAD_REQUEST] #[body = "Failed to deserialize form"] /// Rejection type used if the [`Form`](Form) extractor is unable to /// deserialize the form into the target type. pub struct FailedToDeserializeForm(Error); } define_rejection! { #[status = UNPROCESSABLE_ENTITY] #[body = "Failed to deserialize form body"] /// Rejection type used if the [`Form`](Form) extractor is unable to /// deserialize the form body into the target type. pub struct FailedToDeserializeFormBody(Error); } composite_rejection! { /// Rejection used for [`Form`]. /// /// Contains one variant for each way the [`Form`] extractor can fail. #[deprecated = "because Form is deprecated"] pub enum FormRejection { RawFormRejection, FailedToDeserializeForm, FailedToDeserializeFormBody, } } #[cfg(test)] mod tests { use super::*; use crate::test_helpers::*; use axum::routing::{on, post, MethodFilter}; use axum::Router; use http::header::CONTENT_TYPE; use http::StatusCode; use mime::APPLICATION_WWW_FORM_URLENCODED; use serde::Deserialize; #[tokio::test] async fn supports_multiple_values() { #[derive(Deserialize)] struct Data { #[serde(rename = "value")] values: Vec<String>, } let app = Router::new().route( "/", post(|Form(data): Form<Data>| async move { data.values.join(",") }), ); let client = TestClient::new(app); let res = client .post("/") .header(CONTENT_TYPE, "application/x-www-form-urlencoded") .body("value=one&value=two") .await; assert_eq!(res.status(), StatusCode::OK); assert_eq!(res.text().await, "one,two"); } #[tokio::test] async fn deserialize_error_status_codes() { #[allow(dead_code)] #[derive(Deserialize)] struct Payload { a: i32, } let app = Router::new().route( "/", on( MethodFilter::GET.or(MethodFilter::POST), |_: Form<Payload>| async {}, ), ); let client = TestClient::new(app); let res = client.get("/?a=false").await; assert_eq!(res.status(), StatusCode::BAD_REQUEST); assert_eq!( res.text().await, "Failed to deserialize form: a: invalid digit found in string" ); let res = client .post("/") .header(CONTENT_TYPE, APPLICATION_WWW_FORM_URLENCODED.as_ref()) .body("a=false") .await; assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY); assert_eq!( res.text().await, "Failed to deserialize form body: a: invalid digit found in string" ); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/extract/mod.rs
axum-extra/src/extract/mod.rs
//! Additional extractors. pub mod rejection; #[cfg(feature = "cached")] mod cached; #[cfg(feature = "with-rejection")] mod with_rejection; #[cfg(feature = "form")] mod form; #[cfg(feature = "cookie")] pub mod cookie; #[cfg(feature = "json-deserializer")] mod json_deserializer; #[cfg(feature = "query")] mod query; #[cfg(feature = "multipart")] pub mod multipart; #[cfg(feature = "cached")] pub use self::cached::Cached; #[cfg(feature = "with-rejection")] pub use self::with_rejection::WithRejection; #[cfg(feature = "cookie")] pub use self::cookie::CookieJar; #[cfg(feature = "cookie-private")] pub use self::cookie::PrivateCookieJar; #[cfg(feature = "cookie-signed")] pub use self::cookie::SignedCookieJar; #[cfg(feature = "form")] #[allow(deprecated)] pub use self::form::{Form, FormRejection}; #[cfg(feature = "query")] pub use self::query::OptionalQuery; #[cfg(feature = "query")] #[allow(deprecated)] pub use self::query::{OptionalQueryRejection, Query, QueryRejection}; #[cfg(feature = "multipart")] pub use self::multipart::Multipart; #[cfg(feature = "json-deserializer")] pub use self::json_deserializer::{ JsonDataError, JsonDeserializer, JsonDeserializerRejection, JsonSyntaxError, MissingJsonContentType, }; #[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;
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/extract/rejection.rs
axum-extra/src/extract/rejection.rs
//! Rejection response types. use axum_core::{ __composite_rejection as composite_rejection, __define_rejection as define_rejection, }; define_rejection! { #[status = BAD_REQUEST] #[body = "No host found in request"] /// Rejection type used if the [`Host`](super::Host) extractor is unable to /// resolve a host. pub struct FailedToResolveHost; } composite_rejection! { /// Rejection used for [`Host`](super::Host). /// /// Contains one variant for each way the [`Host`](super::Host) extractor /// can fail. pub enum HostRejection { FailedToResolveHost, } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/extract/query.rs
axum-extra/src/extract/query.rs
#![allow(deprecated)] use axum_core::__composite_rejection as composite_rejection; use axum_core::__define_rejection as define_rejection; use axum_core::extract::FromRequestParts; use http::{request::Parts, Uri}; use serde_core::de::DeserializeOwned; /// Extractor that deserializes query strings into some type. /// /// `T` is expected to implement [`serde::Deserialize`]. /// /// # Deprecated /// /// This extractor used to use a different deserializer under-the-hood but that /// is no longer the case. Now it only uses an older version of the same /// deserializer, purely for ease of transition to the latest version. /// Before switching to `axum::extract::Form`, it is recommended to read the /// [changelog for `serde_html_form v0.3.0`][changelog]. /// /// [changelog]: https://github.com/jplatte/serde_html_form/blob/main/CHANGELOG.md#030 #[deprecated = "see documentation"] #[cfg_attr(docsrs, doc(cfg(feature = "query")))] #[derive(Debug, Clone, Copy, Default)] pub struct Query<T>(pub T); impl<T, S> FromRequestParts<S> for Query<T> where T: DeserializeOwned, S: Send + Sync, { type Rejection = QueryRejection; async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> { let query = parts.uri.query().unwrap_or_default(); let deserializer = serde_html_form::Deserializer::new(form_urlencoded::parse(query.as_bytes())); let value = serde_path_to_error::deserialize(deserializer) .map_err(FailedToDeserializeQueryString::from_err)?; Ok(Self(value)) } } impl<T> Query<T> where T: DeserializeOwned, { /// Attempts to construct a [`Query`] from a reference to a [`Uri`]. /// /// # Example /// ``` /// use axum_extra::extract::Query; /// use http::Uri; /// use serde::Deserialize; /// /// #[derive(Deserialize)] /// struct ExampleParams { /// foo: String, /// bar: u32, /// } /// /// let uri: Uri = "http://example.com/path?foo=hello&bar=42".parse().unwrap(); /// let result: Query<ExampleParams> = Query::try_from_uri(&uri).unwrap(); /// assert_eq!(result.foo, String::from("hello")); /// assert_eq!(result.bar, 42); /// ``` pub fn try_from_uri(value: &Uri) -> Result<Self, QueryRejection> { let query = value.query().unwrap_or_default(); let params = serde_html_form::from_str(query).map_err(FailedToDeserializeQueryString::from_err)?; Ok(Self(params)) } } axum_core::__impl_deref!(Query); define_rejection! { #[status = BAD_REQUEST] #[body = "Failed to deserialize query string"] /// Rejection type used if the [`Query`] extractor is unable to /// deserialize the query string into the target type. pub struct FailedToDeserializeQueryString(Error); } composite_rejection! { /// Rejection used for [`Query`]. /// /// Contains one variant for each way the [`Query`] extractor can fail. #[deprecated = "because Query is deprecated"] pub enum QueryRejection { FailedToDeserializeQueryString, } } /// Extractor that deserializes query strings into `None` if no query parameters are present. /// /// Otherwise behaviour is identical to [`Query`][axum::extract::Query]. /// `T` is expected to implement [`serde::Deserialize`]. /// /// # Example /// /// ```rust,no_run /// use axum::{routing::get, Router}; /// use axum_extra::extract::OptionalQuery; /// use serde::Deserialize; /// /// #[derive(Deserialize)] /// struct Pagination { /// page: usize, /// per_page: usize, /// } /// /// // This will parse query strings like `?page=2&per_page=30` into `Some(Pagination)` and /// // empty query string into `None` /// async fn list_things(OptionalQuery(pagination): OptionalQuery<Pagination>) { /// match pagination { /// Some(Pagination{ page, per_page }) => { /* return specified page */ }, /// None => { /* return fist page */ } /// } /// // ... /// } /// /// let app = Router::new().route("/list_things", get(list_things)); /// # let _: Router = app; /// ``` /// /// If the query string cannot be parsed it will reject the request with a `400 /// Bad Request` response. #[cfg_attr(docsrs, doc(cfg(feature = "query")))] #[derive(Debug, Clone, Copy, Default)] pub struct OptionalQuery<T>(pub Option<T>); impl<T, S> FromRequestParts<S> for OptionalQuery<T> where T: DeserializeOwned, S: Send + Sync, { type Rejection = OptionalQueryRejection; async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> { if let Some(query) = parts.uri.query() { let deserializer = serde_html_form::Deserializer::new(form_urlencoded::parse(query.as_bytes())); let value = serde_path_to_error::deserialize(deserializer) .map_err(FailedToDeserializeQueryString::from_err)?; Ok(Self(Some(value))) } else { Ok(Self(None)) } } } impl<T> std::ops::Deref for OptionalQuery<T> { type Target = Option<T>; #[inline] fn deref(&self) -> &Self::Target { &self.0 } } impl<T> std::ops::DerefMut for OptionalQuery<T> { #[inline] fn deref_mut(&mut self) -> &mut Self::Target { &mut self.0 } } composite_rejection! { /// Rejection used for [`OptionalQuery`]. /// /// Contains one variant for each way the [`OptionalQuery`] extractor can fail. pub enum OptionalQueryRejection { FailedToDeserializeQueryString, } } #[cfg(test)] mod tests { use super::*; use crate::test_helpers::*; use axum::routing::{get, post}; use axum::Router; use http::header::CONTENT_TYPE; use http::StatusCode; use serde::Deserialize; #[tokio::test] async fn query_supports_multiple_values() { #[derive(Deserialize)] struct Data { #[serde(rename = "value")] values: Vec<String>, } let app = Router::new().route( "/", post(|Query(data): Query<Data>| async move { data.values.join(",") }), ); let client = TestClient::new(app); let res = client .post("/?value=one&value=two") .header(CONTENT_TYPE, "application/x-www-form-urlencoded") .body("") .await; assert_eq!(res.status(), StatusCode::OK); assert_eq!(res.text().await, "one,two"); } #[tokio::test] async fn correct_rejection_status_code() { #[derive(Deserialize)] #[allow(dead_code)] struct Params { n: i32, } async fn handler(_: Query<Params>) {} let app = Router::new().route("/", get(handler)); let client = TestClient::new(app); let res = client.get("/?n=hi").await; assert_eq!(res.status(), StatusCode::BAD_REQUEST); assert_eq!( res.text().await, "Failed to deserialize query string: n: invalid digit found in string" ); } #[tokio::test] async fn optional_query_supports_multiple_values() { #[derive(Deserialize)] struct Data { #[serde(rename = "value")] values: Vec<String>, } let app = Router::new().route( "/", post(|OptionalQuery(data): OptionalQuery<Data>| async move { data.map(|Data { values }| values.join(",")) .unwrap_or("None".to_owned()) }), ); let client = TestClient::new(app); let res = client .post("/?value=one&value=two") .header(CONTENT_TYPE, "application/x-www-form-urlencoded") .body("") .await; assert_eq!(res.status(), StatusCode::OK); assert_eq!(res.text().await, "one,two"); } #[tokio::test] async fn optional_query_deserializes_no_parameters_into_none() { #[derive(Deserialize)] struct Data { value: String, } let app = Router::new().route( "/", post(|OptionalQuery(data): OptionalQuery<Data>| async move { match data { None => "None".into(), Some(data) => data.value, } }), ); let client = TestClient::new(app); let res = client.post("/").body("").await; assert_eq!(res.status(), StatusCode::OK); assert_eq!(res.text().await, "None"); } #[tokio::test] async fn optional_query_preserves_parsing_errors() { #[derive(Deserialize)] struct Data { value: String, } let app = Router::new().route( "/", post(|OptionalQuery(data): OptionalQuery<Data>| async move { match data { None => "None".into(), Some(data) => data.value, } }), ); let client = TestClient::new(app); let res = client .post("/?other=something") .header(CONTENT_TYPE, "application/x-www-form-urlencoded") .body("") .await; assert_eq!(res.status(), StatusCode::BAD_REQUEST); } #[test] fn test_try_from_uri() { #[derive(Deserialize)] struct TestQueryParams { foo: Vec<String>, bar: u32, } let uri: Uri = "http://example.com/path?foo=hello&bar=42&foo=goodbye" .parse() .unwrap(); let result: Query<TestQueryParams> = Query::try_from_uri(&uri).unwrap(); assert_eq!(result.foo, [String::from("hello"), String::from("goodbye")]); assert_eq!(result.bar, 42); } #[test] fn test_try_from_uri_with_invalid_query() { #[derive(Deserialize)] struct TestQueryParams { _foo: String, _bar: u32, } let uri: Uri = "http://example.com/path?foo=hello&bar=invalid" .parse() .unwrap(); let result: Result<Query<TestQueryParams>, _> = Query::try_from_uri(&uri); assert!(result.is_err()); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/extract/json_deserializer.rs
axum-extra/src/extract/json_deserializer.rs
use axum_core::__composite_rejection as composite_rejection; use axum_core::__define_rejection as define_rejection; use axum_core::extract::rejection::BytesRejection; use axum_core::extract::{FromRequest, Request}; use bytes::Bytes; use http::{header, HeaderMap}; use serde_core::Deserialize; use std::marker::PhantomData; /// JSON Extractor for zero-copy deserialization. /// /// Deserialize request bodies into some type that implements [`serde::Deserialize<'de>`][serde::Deserialize]. /// Parsing JSON is delayed until [`deserialize`](JsonDeserializer::deserialize) is called. /// If the type implements [`serde::de::DeserializeOwned`], the [`Json`](axum::Json) extractor should /// be preferred. /// /// The request will be rejected (and a [`JsonDeserializerRejection`] will be returned) if: /// /// - The request doesn't have a `Content-Type: application/json` (or similar) header. /// - Buffering the request body fails. /// /// Additionally, a `JsonRejection` error will be returned, when calling `deserialize` if: /// /// - The body doesn't contain syntactically valid JSON. /// - The body contains syntactically valid JSON, but it couldn't be deserialized into the target type. /// - Attempting to deserialize escaped JSON into a type that must be borrowed (e.g. `&'a str`). /// /// ⚠️ `serde` will implicitly try to borrow for `&str` and `&[u8]` types, but will error if the /// input contains escaped characters. Use `Cow<'a, str>` or `Cow<'a, [u8]>`, with the /// `#[serde(borrow)]` attribute, to allow serde to fall back to an owned type when encountering /// escaped characters. /// /// ⚠️ Since parsing JSON requires consuming the request body, the `Json` extractor must be /// *last* if there are multiple extractors in a handler. /// See ["the order of extractors"][order-of-extractors] /// /// [order-of-extractors]: axum::extract#the-order-of-extractors /// /// See [`JsonDeserializerRejection`] for more details. /// /// # Example /// /// ```rust,no_run /// use axum::{ /// routing::post, /// Router, /// response::{IntoResponse, Response} /// }; /// use axum_extra::extract::JsonDeserializer; /// use serde::Deserialize; /// use std::borrow::Cow; /// use http::StatusCode; /// /// #[derive(Deserialize)] /// struct Data<'a> { /// #[serde(borrow)] /// borrow_text: Cow<'a, str>, /// #[serde(borrow)] /// borrow_bytes: Cow<'a, [u8]>, /// borrow_dangerous: &'a str, /// not_borrowed: String, /// } /// /// async fn upload(deserializer: JsonDeserializer<Data<'_>>) -> Response { /// let data = match deserializer.deserialize() { /// Ok(data) => data, /// Err(e) => return e.into_response(), /// }; /// /// // payload is a `Data` with borrowed data from `deserializer`, /// // which owns the request body (`Bytes`). /// /// StatusCode::OK.into_response() /// } /// /// let app = Router::new().route("/upload", post(upload)); /// # let _: Router = app; /// ``` #[derive(Debug, Clone, Default)] #[cfg_attr(docsrs, doc(cfg(feature = "json-deserializer")))] pub struct JsonDeserializer<T> { bytes: Bytes, _marker: PhantomData<T>, } impl<T, S> FromRequest<S> for JsonDeserializer<T> where T: Deserialize<'static>, S: Send + Sync, { type Rejection = JsonDeserializerRejection; async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> { if json_content_type(req.headers()) { let bytes = Bytes::from_request(req, state).await?; Ok(Self { bytes, _marker: PhantomData, }) } else { Err(MissingJsonContentType.into()) } } } impl<'de, 'a: 'de, T> JsonDeserializer<T> where T: Deserialize<'de>, { /// Deserialize the request body into the target type. /// See [`JsonDeserializer`] for more details. pub fn deserialize(&'a self) -> Result<T, JsonDeserializerRejection> { let deserializer = &mut serde_json::Deserializer::from_slice(&self.bytes); let value = match serde_path_to_error::deserialize(deserializer) { Ok(value) => value, Err(err) => { let rejection = match err.inner().classify() { serde_json::error::Category::Data => JsonDataError::from_err(err).into(), serde_json::error::Category::Syntax | serde_json::error::Category::Eof => { JsonSyntaxError::from_err(err).into() } serde_json::error::Category::Io => { if cfg!(debug_assertions) { // we don't use `serde_json::from_reader` and instead always buffer // bodies first, so we shouldn't encounter any IO errors unreachable!() } else { JsonSyntaxError::from_err(err).into() } } }; return Err(rejection); } }; Ok(value) } } define_rejection! { #[status = UNPROCESSABLE_ENTITY] #[body = "Failed to deserialize the JSON body into the target type"] #[cfg_attr(docsrs, doc(cfg(feature = "json-deserializer")))] /// Rejection type for [`JsonDeserializer`]. /// /// This rejection is used if the request body is syntactically valid JSON but couldn't be /// deserialized into the target type. pub struct JsonDataError(Error); } define_rejection! { #[status = BAD_REQUEST] #[body = "Failed to parse the request body as JSON"] #[cfg_attr(docsrs, doc(cfg(feature = "json-deserializer")))] /// Rejection type for [`JsonDeserializer`]. /// /// This rejection is used if the request body didn't contain syntactically valid JSON. pub struct JsonSyntaxError(Error); } define_rejection! { #[status = UNSUPPORTED_MEDIA_TYPE] #[body = "Expected request with `Content-Type: application/json`"] #[cfg_attr(docsrs, doc(cfg(feature = "json-deserializer")))] /// Rejection type for [`JsonDeserializer`] used if the `Content-Type` /// header is missing. pub struct MissingJsonContentType; } composite_rejection! { /// Rejection used for [`JsonDeserializer`]. /// /// Contains one variant for each way the [`JsonDeserializer`] extractor /// can fail. #[cfg_attr(docsrs, doc(cfg(feature = "json-deserializer")))] pub enum JsonDeserializerRejection { JsonDataError, JsonSyntaxError, MissingJsonContentType, BytesRejection, } } fn json_content_type(headers: &HeaderMap) -> bool { let Some(content_type) = headers.get(header::CONTENT_TYPE) else { return false; }; let Ok(content_type) = content_type.to_str() else { return false; }; let Ok(mime) = content_type.parse::<mime::Mime>() else { return false; }; let is_json_content_type = mime.type_() == "application" && (mime.subtype() == "json" || mime.suffix().is_some_and(|name| name == "json")); is_json_content_type } #[cfg(test)] mod tests { use super::*; use crate::test_helpers::*; use axum::{ response::{IntoResponse, Response}, routing::post, Router, }; use http::StatusCode; use serde::Deserialize; use serde_json::{json, Value}; use std::borrow::Cow; #[tokio::test] async fn deserialize_body() { #[derive(Debug, Deserialize)] struct Input<'a> { #[serde(borrow)] foo: Cow<'a, str>, } async fn handler(deserializer: JsonDeserializer<Input<'_>>) -> Response { match deserializer.deserialize() { Ok(input) => { assert!(matches!(input.foo, Cow::Borrowed(_))); input.foo.into_owned().into_response() } Err(e) => e.into_response(), } } let app = Router::new().route("/", post(handler)); let client = TestClient::new(app); let res = client.post("/").json(&json!({ "foo": "bar" })).await; let body = res.text().await; assert_eq!(body, "bar"); } #[tokio::test] async fn deserialize_body_escaped_to_cow() { #[derive(Debug, Deserialize)] struct Input<'a> { #[serde(borrow)] foo: Cow<'a, str>, } async fn handler(deserializer: JsonDeserializer<Input<'_>>) -> Response { match deserializer.deserialize() { Ok(Input { foo }) => { let Cow::Owned(foo) = foo else { panic!("Deserializer is expected to fallback to Cow::Owned when encountering escaped characters") }; foo.into_response() } Err(e) => e.into_response(), } } let app = Router::new().route("/", post(handler)); let client = TestClient::new(app); // The escaped characters prevent serde_json from borrowing. let res = client.post("/").json(&json!({ "foo": "\"bar\"" })).await; let body = res.text().await; assert_eq!(body, r#""bar""#); } #[tokio::test] async fn deserialize_body_escaped_to_str() { #[derive(Debug, Deserialize)] struct Input<'a> { // Explicit `#[serde(borrow)]` attribute is not required for `&str` or &[u8]. // See: https://serde.rs/lifetimes.html#borrowing-data-in-a-derived-impl foo: &'a str, } async fn handler(deserializer: JsonDeserializer<Input<'_>>) -> Response { match deserializer.deserialize() { Ok(Input { foo }) => foo.to_owned().into_response(), Err(e) => e.into_response(), } } let app = Router::new().route("/", post(handler)); let client = TestClient::new(app); let res = client.post("/").json(&json!({ "foo": "good" })).await; let body = res.text().await; assert_eq!(body, "good"); let res = client.post("/").json(&json!({ "foo": "\"bad\"" })).await; assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY); let body_text = res.text().await; assert_eq!( body_text, "Failed to deserialize the JSON body into the target type: foo: invalid type: string \"\\\"bad\\\"\", expected a borrowed string at line 1 column 16" ); } #[tokio::test] async fn consume_body_to_json_requires_json_content_type() { #[derive(Debug, Deserialize)] struct Input<'a> { #[allow(dead_code)] foo: Cow<'a, str>, } async fn handler(_deserializer: JsonDeserializer<Input<'_>>) -> Response { panic!("This handler should not be called") } let app = Router::new().route("/", post(handler)); let client = TestClient::new(app); let res = client.post("/").body(r#"{ "foo": "bar" }"#).await; let status = res.status(); assert_eq!(status, StatusCode::UNSUPPORTED_MEDIA_TYPE); } #[tokio::test] async fn json_content_types() { async fn valid_json_content_type(content_type: &str) -> bool { println!("testing {content_type:?}"); async fn handler(_deserializer: JsonDeserializer<Value>) -> Response { StatusCode::OK.into_response() } let app = Router::new().route("/", post(handler)); let res = TestClient::new(app) .post("/") .header("content-type", content_type) .body("{}") .await; res.status() == StatusCode::OK } assert!(valid_json_content_type("application/json").await); assert!(valid_json_content_type("application/json; charset=utf-8").await); assert!(valid_json_content_type("application/json;charset=utf-8").await); assert!(valid_json_content_type("application/cloudevents+json").await); assert!(!valid_json_content_type("text/json").await); } #[tokio::test] async fn invalid_json_syntax() { async fn handler(deserializer: JsonDeserializer<Value>) -> Response { match deserializer.deserialize() { Ok(_) => panic!("Should have matched `Err`"), Err(e) => e.into_response(), } } let app = Router::new().route("/", post(handler)); let client = TestClient::new(app); let res = client .post("/") .body("{") .header("content-type", "application/json") .await; assert_eq!(res.status(), StatusCode::BAD_REQUEST); } #[derive(Deserialize)] struct Foo { #[allow(dead_code)] a: i32, #[allow(dead_code)] b: Vec<Bar>, } #[derive(Deserialize)] struct Bar { #[allow(dead_code)] x: i32, #[allow(dead_code)] y: i32, } #[tokio::test] async fn invalid_json_data() { async fn handler(deserializer: JsonDeserializer<Foo>) -> Response { match deserializer.deserialize() { Ok(_) => panic!("Should have matched `Err`"), Err(e) => e.into_response(), } } let app = Router::new().route("/", post(handler)); let client = TestClient::new(app); let res = client .post("/") .body("{\"a\": 1, \"b\": [{\"x\": 2}]}") .header("content-type", "application/json") .await; assert_eq!(res.status(), StatusCode::UNPROCESSABLE_ENTITY); let body_text = res.text().await; assert_eq!( body_text, "Failed to deserialize the JSON body into the target type: b[0]: missing field `y` at line 1 column 23" ); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/extract/cookie/mod.rs
axum-extra/src/extract/cookie/mod.rs
//! Cookie parsing and cookie jar management. //! //! See [`CookieJar`], [`SignedCookieJar`], and [`PrivateCookieJar`] for more details. use axum_core::{ extract::FromRequestParts, response::{IntoResponse, IntoResponseParts, Response, ResponseParts}, }; use http::{ header::{COOKIE, SET_COOKIE}, request::Parts, HeaderMap, }; use std::convert::Infallible; #[cfg(feature = "cookie-private")] mod private; #[cfg(feature = "cookie-signed")] mod signed; #[cfg(feature = "cookie-private")] pub use self::private::PrivateCookieJar; #[cfg(feature = "cookie-signed")] pub use self::signed::SignedCookieJar; pub use cookie::{Cookie, Expiration, SameSite}; #[cfg(any(feature = "cookie-signed", feature = "cookie-private"))] pub use cookie::Key; /// Extractor that grabs cookies from the request and manages the jar. /// /// Note that methods like [`CookieJar::add`], [`CookieJar::remove`], etc updates the [`CookieJar`] /// and returns it. This value _must_ be returned from the handler as part of the response for the /// changes to be propagated. /// /// # Example /// /// ```rust /// use axum::{ /// Router, /// routing::{post, get}, /// response::{IntoResponse, Redirect}, /// http::StatusCode, /// }; /// use axum_extra::{ /// TypedHeader, /// headers::authorization::{Authorization, Bearer}, /// extract::cookie::{CookieJar, Cookie}, /// }; /// /// async fn create_session( /// TypedHeader(auth): TypedHeader<Authorization<Bearer>>, /// jar: CookieJar, /// ) -> Result<(CookieJar, Redirect), StatusCode> { /// if let Some(session_id) = authorize_and_create_session(auth.token()).await { /// Ok(( /// // the updated jar must be returned for the changes /// // to be included in the response /// jar.add(Cookie::new("session_id", session_id)), /// Redirect::to("/me"), /// )) /// } else { /// Err(StatusCode::UNAUTHORIZED) /// } /// } /// /// async fn me(jar: CookieJar) -> Result<(), StatusCode> { /// if let Some(session_id) = jar.get("session_id") { /// // fetch and render user... /// # Ok(()) /// } else { /// Err(StatusCode::UNAUTHORIZED) /// } /// } /// /// async fn authorize_and_create_session(token: &str) -> Option<String> { /// // authorize the user and create a session... /// # todo!() /// } /// /// let app = Router::new() /// .route("/sessions", post(create_session)) /// .route("/me", get(me)); /// # let app: Router = app; /// ``` #[must_use = "`CookieJar` should be returned as part of a `Response`, otherwise it does nothing."] #[derive(Debug, Default, Clone)] pub struct CookieJar { jar: cookie::CookieJar, } impl<S> FromRequestParts<S> for CookieJar where S: Send + Sync, { type Rejection = Infallible; async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> { Ok(Self::from_headers(&parts.headers)) } } fn cookies_from_request(headers: &HeaderMap) -> impl Iterator<Item = Cookie<'static>> + '_ { headers .get_all(COOKIE) .into_iter() .filter_map(|value| value.to_str().ok()) .flat_map(|value| value.split(';')) .filter_map(|cookie| Cookie::parse_encoded(cookie.to_owned()).ok()) } impl CookieJar { /// Create a new `CookieJar` from a map of request headers. /// /// The cookies in `headers` will be added to the jar. /// /// This is intended to be used in middleware and other places where it might be difficult to /// run extractors. Normally you should create `CookieJar`s through [`FromRequestParts`]. /// /// [`FromRequestParts`]: axum::extract::FromRequestParts pub fn from_headers(headers: &HeaderMap) -> Self { let mut jar = cookie::CookieJar::new(); for cookie in cookies_from_request(headers) { jar.add_original(cookie); } Self { jar } } /// Create a new empty `CookieJar`. /// /// This is intended to be used in middleware and other places where it might be difficult to /// run extractors. Normally you should create `CookieJar`s through [`FromRequestParts`]. /// /// If you need a jar that contains the headers from a request use `impl From<&HeaderMap> for /// CookieJar`. /// /// [`FromRequestParts`]: axum::extract::FromRequestParts pub fn new() -> Self { Self::default() } /// Get a cookie from the jar. /// /// # Example /// /// ```rust /// use axum_extra::extract::cookie::CookieJar; /// use axum::response::IntoResponse; /// /// async fn handle(jar: CookieJar) { /// let value: Option<String> = jar /// .get("foo") /// .map(|cookie| cookie.value().to_owned()); /// } /// ``` #[must_use] pub fn get(&self, name: &str) -> Option<&Cookie<'static>> { self.jar.get(name) } /// Remove a cookie from the jar. /// /// # Example /// /// ```rust /// use axum_extra::extract::cookie::{CookieJar, Cookie}; /// use axum::response::IntoResponse; /// /// async fn handle(jar: CookieJar) -> CookieJar { /// jar.remove(Cookie::from("foo")) /// } /// ``` pub fn remove<C: Into<Cookie<'static>>>(mut self, cookie: C) -> Self { self.jar.remove(cookie); self } /// Add a cookie to the jar. /// /// The value will automatically be percent-encoded. /// /// # Example /// /// ```rust /// use axum_extra::extract::cookie::{CookieJar, Cookie}; /// use axum::response::IntoResponse; /// /// async fn handle(jar: CookieJar) -> CookieJar { /// jar.add(Cookie::new("foo", "bar")) /// } /// ``` #[allow(clippy::should_implement_trait)] pub fn add<C: Into<Cookie<'static>>>(mut self, cookie: C) -> Self { self.jar.add(cookie); self } /// Get an iterator over all cookies in the jar. pub fn iter(&self) -> impl Iterator<Item = &'_ Cookie<'static>> { self.jar.iter() } } impl IntoResponseParts for CookieJar { type Error = Infallible; fn into_response_parts(self, mut res: ResponseParts) -> Result<ResponseParts, Self::Error> { set_cookies(&self.jar, res.headers_mut()); Ok(res) } } impl IntoResponse for CookieJar { fn into_response(self) -> Response { (self, ()).into_response() } } fn set_cookies(jar: &cookie::CookieJar, headers: &mut HeaderMap) { for cookie in jar.delta() { if let Ok(header_value) = cookie.encoded().to_string().parse() { headers.append(SET_COOKIE, header_value); } } // we don't need to call `jar.reset_delta()` because `into_response_parts` consumes the cookie // jar so it cannot be called multiple times. } #[cfg(test)] mod tests { use super::*; use axum::{body::Body, extract::FromRef, http::Request, routing::get, Router}; use http_body_util::BodyExt; use tower::ServiceExt; macro_rules! cookie_test { ($name:ident, $jar:ty) => { #[tokio::test] async fn $name() { async fn set_cookie(jar: $jar) -> impl IntoResponse { jar.add(Cookie::new("key", "value")) } async fn get_cookie(jar: $jar) -> impl IntoResponse { jar.get("key").unwrap().value().to_owned() } async fn remove_cookie(jar: $jar) -> impl IntoResponse { jar.remove(Cookie::from("key")) } let state = AppState { key: Key::generate(), custom_key: CustomKey(Key::generate()), }; let app = Router::new() .route("/set", get(set_cookie)) .route("/get", get(get_cookie)) .route("/remove", get(remove_cookie)) .with_state(state); let res = app .clone() .oneshot(Request::builder().uri("/set").body(Body::empty()).unwrap()) .await .unwrap(); let cookie_value = res.headers()["set-cookie"].to_str().unwrap(); let res = app .clone() .oneshot( Request::builder() .uri("/get") .header("cookie", cookie_value) .body(Body::empty()) .unwrap(), ) .await .unwrap(); let body = body_text(res).await; assert_eq!(body, "value"); let res = app .clone() .oneshot( Request::builder() .uri("/remove") .header("cookie", cookie_value) .body(Body::empty()) .unwrap(), ) .await .unwrap(); assert!(res.headers()["set-cookie"] .to_str() .unwrap() .contains("key=;")); } }; } cookie_test!(plaintext_cookies, CookieJar); #[cfg(feature = "cookie-signed")] cookie_test!(signed_cookies, SignedCookieJar); #[cfg(feature = "cookie-signed")] cookie_test!(signed_cookies_with_custom_key, SignedCookieJar<CustomKey>); #[cfg(feature = "cookie-private")] cookie_test!(private_cookies, PrivateCookieJar); #[cfg(feature = "cookie-private")] cookie_test!(private_cookies_with_custom_key, PrivateCookieJar<CustomKey>); #[derive(Clone)] struct AppState { key: Key, custom_key: CustomKey, } impl FromRef<AppState> for Key { fn from_ref(state: &AppState) -> Self { state.key.clone() } } impl FromRef<AppState> for CustomKey { fn from_ref(state: &AppState) -> Self { state.custom_key.clone() } } #[derive(Clone)] struct CustomKey(Key); impl From<CustomKey> for Key { fn from(custom: CustomKey) -> Self { custom.0 } } #[cfg(feature = "cookie-signed")] #[tokio::test] async fn signed_cannot_access_invalid_cookies() { async fn get_cookie(jar: SignedCookieJar) -> impl IntoResponse { format!("{:?}", jar.get("key")) } let state = AppState { key: Key::generate(), custom_key: CustomKey(Key::generate()), }; let app = Router::new() .route("/get", get(get_cookie)) .with_state(state); let res = app .clone() .oneshot( Request::builder() .uri("/get") .header("cookie", "key=value") .body(Body::empty()) .unwrap(), ) .await .unwrap(); let body = body_text(res).await; assert_eq!(body, "None"); } async fn body_text<B>(body: B) -> String where B: axum::body::HttpBody, B::Error: std::fmt::Debug, { let bytes = body.collect().await.unwrap().to_bytes(); String::from_utf8(bytes.to_vec()).unwrap() } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/extract/cookie/signed.rs
axum-extra/src/extract/cookie/signed.rs
use super::{cookies_from_request, set_cookies}; use axum_core::{ extract::{FromRef, FromRequestParts}, response::{IntoResponse, IntoResponseParts, Response, ResponseParts}, }; use cookie::SignedJar; use cookie::{Cookie, Key}; use http::{request::Parts, HeaderMap}; use std::{convert::Infallible, fmt, marker::PhantomData}; /// Extractor that grabs signed cookies from the request and manages the jar. /// /// All cookies will be signed and verified with a [`Key`]. Do not use this to store private data /// as the values are still transmitted in plaintext. /// /// Note that methods like [`SignedCookieJar::add`], [`SignedCookieJar::remove`], etc updates the /// [`SignedCookieJar`] and returns it. This value _must_ be returned from the handler as part of /// the response for the changes to be propagated. /// /// # Example /// /// ```rust /// use axum::{ /// Router, /// routing::{post, get}, /// extract::FromRef, /// response::{IntoResponse, Redirect}, /// http::StatusCode, /// }; /// use axum_extra::{ /// TypedHeader, /// headers::authorization::{Authorization, Bearer}, /// extract::cookie::{SignedCookieJar, Cookie, Key}, /// }; /// /// async fn create_session( /// TypedHeader(auth): TypedHeader<Authorization<Bearer>>, /// jar: SignedCookieJar, /// ) -> Result<(SignedCookieJar, Redirect), StatusCode> { /// if let Some(session_id) = authorize_and_create_session(auth.token()).await { /// Ok(( /// // the updated jar must be returned for the changes /// // to be included in the response /// jar.add(Cookie::new("session_id", session_id)), /// Redirect::to("/me"), /// )) /// } else { /// Err(StatusCode::UNAUTHORIZED) /// } /// } /// /// async fn me(jar: SignedCookieJar) -> Result<(), StatusCode> { /// if let Some(session_id) = jar.get("session_id") { /// // fetch and render user... /// # Ok(()) /// } else { /// Err(StatusCode::UNAUTHORIZED) /// } /// } /// /// async fn authorize_and_create_session(token: &str) -> Option<String> { /// // authorize the user and create a session... /// # todo!() /// } /// /// // our application state /// #[derive(Clone)] /// struct AppState { /// // that holds the key used to sign cookies /// key: Key, /// } /// /// // this impl tells `SignedCookieJar` how to access the key from our state /// impl FromRef<AppState> for Key { /// fn from_ref(state: &AppState) -> Self { /// state.key.clone() /// } /// } /// /// let state = AppState { /// // Generate a secure key /// // /// // You probably don't wanna generate a new one each time the app starts though /// key: Key::generate(), /// }; /// /// let app = Router::new() /// .route("/sessions", post(create_session)) /// .route("/me", get(me)) /// .with_state(state); /// # let _: axum::Router = app; /// ``` /// If you have been using `Arc<AppState>` you cannot implement `FromRef<Arc<AppState>> for Key`. /// You can use a new type instead: /// /// ```rust /// # use axum::extract::FromRef; /// # use axum_extra::extract::cookie::{PrivateCookieJar, Cookie, Key}; /// use std::sync::Arc; /// use std::ops::Deref; /// /// #[derive(Clone)] /// struct AppState(Arc<InnerState>); /// /// // deref so you can still access the inner fields easily /// impl Deref for AppState { /// type Target = InnerState; /// /// fn deref(&self) -> &Self::Target { /// &*self.0 /// } /// } /// /// struct InnerState { /// key: Key /// } /// /// impl FromRef<AppState> for Key { /// fn from_ref(state: &AppState) -> Self { /// state.0.key.clone() /// } /// } /// ``` #[must_use = "`SignedCookieJar` should be returned as part of a `Response`, otherwise it does nothing."] pub struct SignedCookieJar<K = Key> { jar: cookie::CookieJar, key: Key, // The key used to extract the key. Allows users to use multiple keys for different // jars. Maybe a library wants its own key. _marker: PhantomData<K>, } impl<K> fmt::Debug for SignedCookieJar<K> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("SignedCookieJar") .field("jar", &self.jar) .field("key", &"REDACTED") .finish() } } impl<S, K> FromRequestParts<S> for SignedCookieJar<K> where S: Send + Sync, K: FromRef<S> + Into<Key>, { type Rejection = Infallible; async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { let k = K::from_ref(state); let key = k.into(); let SignedCookieJar { jar, key, _marker: _, } = SignedCookieJar::from_headers(&parts.headers, key); Ok(Self { jar, key, _marker: PhantomData, }) } } impl SignedCookieJar { /// Create a new `SignedCookieJar` from a map of request headers. /// /// The valid cookies in `headers` will be added to the jar. /// /// This is intended to be used in middleware and other places where it might be difficult to /// run extractors. Normally you should create `SignedCookieJar`s through [`FromRequestParts`]. /// /// [`FromRequestParts`]: axum::extract::FromRequestParts pub fn from_headers(headers: &HeaderMap, key: Key) -> Self { let mut jar = cookie::CookieJar::new(); let mut signed_jar = jar.signed_mut(&key); for cookie in cookies_from_request(headers) { if let Some(cookie) = signed_jar.verify(cookie) { signed_jar.add_original(cookie); } } Self { jar, key, _marker: PhantomData, } } /// Create a new empty `SignedCookieJar`. /// /// This is intended to be used in middleware and other places where it might be difficult to /// run extractors. Normally you should create `SignedCookieJar`s through [`FromRequestParts`]. /// /// [`FromRequestParts`]: axum::extract::FromRequestParts pub fn new(key: Key) -> Self { Self { jar: Default::default(), key, _marker: PhantomData, } } } impl<K> SignedCookieJar<K> { /// Get a cookie from the jar. /// /// If the cookie exists and its authenticity and integrity can be verified then it is returned /// in plaintext. /// /// # Example /// /// ```rust /// use axum_extra::extract::cookie::SignedCookieJar; /// use axum::response::IntoResponse; /// /// async fn handle(jar: SignedCookieJar) { /// let value: Option<String> = jar /// .get("foo") /// .map(|cookie| cookie.value().to_owned()); /// } /// ``` #[must_use] pub fn get(&self, name: &str) -> Option<Cookie<'static>> { self.signed_jar().get(name) } /// Remove a cookie from the jar. /// /// # Example /// /// ```rust /// use axum_extra::extract::cookie::{SignedCookieJar, Cookie}; /// use axum::response::IntoResponse; /// /// async fn handle(jar: SignedCookieJar) -> SignedCookieJar { /// jar.remove(Cookie::from("foo")) /// } /// ``` pub fn remove<C: Into<Cookie<'static>>>(mut self, cookie: C) -> Self { self.signed_jar_mut().remove(cookie); self } /// Add a cookie to the jar. /// /// The value will automatically be percent-encoded. /// /// # Example /// /// ```rust /// use axum_extra::extract::cookie::{SignedCookieJar, Cookie}; /// use axum::response::IntoResponse; /// /// async fn handle(jar: SignedCookieJar) -> SignedCookieJar { /// jar.add(Cookie::new("foo", "bar")) /// } /// ``` #[allow(clippy::should_implement_trait)] pub fn add<C: Into<Cookie<'static>>>(mut self, cookie: C) -> Self { self.signed_jar_mut().add(cookie); self } /// Verifies the authenticity and integrity of `cookie`, returning the plaintext version if /// verification succeeds or `None` otherwise. #[must_use] pub fn verify(&self, cookie: Cookie<'static>) -> Option<Cookie<'static>> { self.signed_jar().verify(cookie) } /// Get an iterator over all cookies in the jar. /// /// Only cookies with valid authenticity and integrity are yielded by the iterator. pub fn iter(&self) -> impl Iterator<Item = Cookie<'static>> + '_ { SignedCookieJarIter { jar: self, iter: self.jar.iter(), } } fn signed_jar(&self) -> SignedJar<&'_ cookie::CookieJar> { self.jar.signed(&self.key) } fn signed_jar_mut(&mut self) -> SignedJar<&'_ mut cookie::CookieJar> { self.jar.signed_mut(&self.key) } } impl<K> IntoResponseParts for SignedCookieJar<K> { type Error = Infallible; fn into_response_parts(self, mut res: ResponseParts) -> Result<ResponseParts, Self::Error> { set_cookies(&self.jar, res.headers_mut()); Ok(res) } } impl<K> IntoResponse for SignedCookieJar<K> { fn into_response(self) -> Response { (self, ()).into_response() } } #[must_use = "iterators are lazy and do nothing unless consumed"] struct SignedCookieJarIter<'a, K> { jar: &'a SignedCookieJar<K>, iter: cookie::Iter<'a>, } impl<K> Iterator for SignedCookieJarIter<'_, K> { type Item = Cookie<'static>; fn next(&mut self) -> Option<Self::Item> { loop { let cookie = self.iter.next()?; if let Some(cookie) = self.jar.get(cookie.name()) { return Some(cookie); } } } } impl<K> Clone for SignedCookieJar<K> { fn clone(&self) -> Self { Self { jar: self.jar.clone(), key: self.key.clone(), _marker: self._marker, } } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/extract/cookie/private.rs
axum-extra/src/extract/cookie/private.rs
use super::{cookies_from_request, set_cookies, Cookie, Key}; use axum_core::{ extract::{FromRef, FromRequestParts}, response::{IntoResponse, IntoResponseParts, Response, ResponseParts}, }; use cookie::PrivateJar; use http::{request::Parts, HeaderMap}; use std::{convert::Infallible, fmt, marker::PhantomData}; /// Extractor that grabs private cookies from the request and manages the jar. /// /// All cookies will be private and encrypted with a [`Key`]. This makes it suitable for storing /// private data. /// /// Note that methods like [`PrivateCookieJar::add`], [`PrivateCookieJar::remove`], etc updates the /// [`PrivateCookieJar`] and returns it. This value _must_ be returned from the handler as part of /// the response for the changes to be propagated. /// /// # Example /// /// ```rust /// use axum::{ /// Router, /// routing::{post, get}, /// extract::FromRef, /// response::{IntoResponse, Redirect}, /// http::StatusCode, /// }; /// use axum_extra::{ /// TypedHeader, /// headers::authorization::{Authorization, Bearer}, /// extract::cookie::{PrivateCookieJar, Cookie, Key}, /// }; /// /// async fn set_secret( /// jar: PrivateCookieJar, /// ) -> (PrivateCookieJar, Redirect) { /// let updated_jar = jar.add(Cookie::new("secret", "secret-data")); /// (updated_jar, Redirect::to("/get")) /// } /// /// async fn get_secret(jar: PrivateCookieJar) { /// if let Some(data) = jar.get("secret") { /// // ... /// } /// } /// /// // our application state /// #[derive(Clone)] /// struct AppState { /// // that holds the key used to encrypt cookies /// key: Key, /// } /// /// // this impl tells `PrivateCookieJar` how to access the key from our state /// impl FromRef<AppState> for Key { /// fn from_ref(state: &AppState) -> Self { /// state.key.clone() /// } /// } /// /// let state = AppState { /// // Generate a secure key /// // /// // You probably don't wanna generate a new one each time the app starts though /// key: Key::generate(), /// }; /// /// let app = Router::new() /// .route("/set", post(set_secret)) /// .route("/get", get(get_secret)) /// .with_state(state); /// # let _: axum::Router = app; /// ``` /// /// If you have been using `Arc<AppState>` you cannot implement `FromRef<Arc<AppState>> for Key`. /// You can use a new type instead: /// /// ```rust /// # use axum::extract::FromRef; /// # use axum_extra::extract::cookie::{PrivateCookieJar, Cookie, Key}; /// use std::sync::Arc; /// use std::ops::Deref; /// /// #[derive(Clone)] /// struct AppState(Arc<InnerState>); /// /// // deref so you can still access the inner fields easily /// impl Deref for AppState { /// type Target = InnerState; /// /// fn deref(&self) -> &Self::Target { /// &self.0 /// } /// } /// /// struct InnerState { /// key: Key /// } /// /// impl FromRef<AppState> for Key { /// fn from_ref(state: &AppState) -> Self { /// state.0.key.clone() /// } /// } /// ``` #[must_use = "`PrivateCookieJar` should be returned as part of a `Response`, otherwise it does nothing."] pub struct PrivateCookieJar<K = Key> { jar: cookie::CookieJar, key: Key, // The key used to extract the key. Allows users to use multiple keys for different // jars. Maybe a library wants its own key. _marker: PhantomData<K>, } impl<K> fmt::Debug for PrivateCookieJar<K> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("PrivateCookieJar") .field("jar", &self.jar) .field("key", &"REDACTED") .finish() } } impl<S, K> FromRequestParts<S> for PrivateCookieJar<K> where S: Send + Sync, K: FromRef<S> + Into<Key>, { type Rejection = Infallible; async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { let k = K::from_ref(state); let key = k.into(); let PrivateCookieJar { jar, key, _marker: _, } = PrivateCookieJar::from_headers(&parts.headers, key); Ok(Self { jar, key, _marker: PhantomData, }) } } impl PrivateCookieJar { /// Create a new `PrivateCookieJar` from a map of request headers. /// /// The valid cookies in `headers` will be added to the jar. /// /// This is intended to be used in middleware and other where places it might be difficult to /// run extractors. Normally you should create `PrivateCookieJar`s through [`FromRequestParts`]. /// /// [`FromRequestParts`]: axum::extract::FromRequestParts pub fn from_headers(headers: &HeaderMap, key: Key) -> Self { let mut jar = cookie::CookieJar::new(); let mut private_jar = jar.private_mut(&key); for cookie in cookies_from_request(headers) { if let Some(cookie) = private_jar.decrypt(cookie) { private_jar.add_original(cookie); } } Self { jar, key, _marker: PhantomData, } } /// Create a new empty `PrivateCookieJarIter`. /// /// This is intended to be used in middleware and other places where it might be difficult to /// run extractors. Normally you should create `PrivateCookieJar`s through [`FromRequestParts`]. /// /// [`FromRequestParts`]: axum::extract::FromRequestParts pub fn new(key: Key) -> Self { Self { jar: Default::default(), key, _marker: PhantomData, } } } impl<K> PrivateCookieJar<K> { /// Get a cookie from the jar. /// /// If the cookie exists and can be decrypted then it is returned in plaintext. /// /// # Example /// /// ```rust /// use axum_extra::extract::cookie::PrivateCookieJar; /// use axum::response::IntoResponse; /// /// async fn handle(jar: PrivateCookieJar) { /// let value: Option<String> = jar /// .get("foo") /// .map(|cookie| cookie.value().to_owned()); /// } /// ``` #[must_use] pub fn get(&self, name: &str) -> Option<Cookie<'static>> { self.private_jar().get(name) } /// Remove a cookie from the jar. /// /// # Example /// /// ```rust /// use axum_extra::extract::cookie::{PrivateCookieJar, Cookie}; /// use axum::response::IntoResponse; /// /// async fn handle(jar: PrivateCookieJar) -> PrivateCookieJar { /// jar.remove(Cookie::from("foo")) /// } /// ``` pub fn remove<C: Into<Cookie<'static>>>(mut self, cookie: C) -> Self { self.private_jar_mut().remove(cookie); self } /// Add a cookie to the jar. /// /// The value will automatically be percent-encoded. /// /// # Example /// /// ```rust /// use axum_extra::extract::cookie::{PrivateCookieJar, Cookie}; /// use axum::response::IntoResponse; /// /// async fn handle(jar: PrivateCookieJar) -> PrivateCookieJar { /// jar.add(Cookie::new("foo", "bar")) /// } /// ``` #[allow(clippy::should_implement_trait)] pub fn add<C: Into<Cookie<'static>>>(mut self, cookie: C) -> Self { self.private_jar_mut().add(cookie); self } /// Authenticates and decrypts `cookie`, returning the plaintext version if decryption succeeds /// or `None` otherwise. #[must_use] pub fn decrypt(&self, cookie: Cookie<'static>) -> Option<Cookie<'static>> { self.private_jar().decrypt(cookie) } /// Get an iterator over all cookies in the jar. /// /// Only cookies with valid authenticity and integrity are yielded by the iterator. pub fn iter(&self) -> impl Iterator<Item = Cookie<'static>> + '_ { PrivateCookieJarIter { jar: self, iter: self.jar.iter(), } } fn private_jar(&self) -> PrivateJar<&'_ cookie::CookieJar> { self.jar.private(&self.key) } fn private_jar_mut(&mut self) -> PrivateJar<&'_ mut cookie::CookieJar> { self.jar.private_mut(&self.key) } } impl<K> IntoResponseParts for PrivateCookieJar<K> { type Error = Infallible; fn into_response_parts(self, mut res: ResponseParts) -> Result<ResponseParts, Self::Error> { set_cookies(&self.jar, res.headers_mut()); Ok(res) } } impl<K> IntoResponse for PrivateCookieJar<K> { fn into_response(self) -> Response { (self, ()).into_response() } } #[must_use = "iterators are lazy and do nothing unless consumed"] struct PrivateCookieJarIter<'a, K> { jar: &'a PrivateCookieJar<K>, iter: cookie::Iter<'a>, } impl<K> Iterator for PrivateCookieJarIter<'_, K> { type Item = Cookie<'static>; fn next(&mut self) -> Option<Self::Item> { loop { let cookie = self.iter.next()?; if let Some(cookie) = self.jar.get(cookie.name()) { return Some(cookie); } } } } impl<K> Clone for PrivateCookieJar<K> { fn clone(&self) -> Self { Self { jar: self.jar.clone(), key: self.key.clone(), _marker: self._marker, } } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/routing/resource.rs
axum-extra/src/routing/resource.rs
use axum::{ handler::Handler, routing::{delete, get, on, post, MethodFilter, MethodRouter}, Router, }; /// A resource which defines a set of conventional CRUD routes. /// /// # Example /// /// ```rust /// use axum::{Router, routing::get, extract::Path}; /// use axum_extra::routing::{RouterExt, Resource}; /// /// let users = Resource::named("users") /// // Define a route for `GET /users` /// .index(|| async {}) /// // `POST /users` /// .create(|| async {}) /// // `GET /users/new` /// .new(|| async {}) /// // `GET /users/{users_id}` /// .show(|Path(user_id): Path<u64>| async {}) /// // `GET /users/{users_id}/edit` /// .edit(|Path(user_id): Path<u64>| async {}) /// // `PUT or PATCH /users/{users_id}` /// .update(|Path(user_id): Path<u64>| async {}) /// // `DELETE /users/{users_id}` /// .destroy(|Path(user_id): Path<u64>| async {}); /// /// let app = Router::new().merge(users); /// # let _: Router = app; /// ``` #[derive(Debug)] #[must_use] pub struct Resource<S = ()> { pub(crate) name: String, pub(crate) router: Router<S>, } impl<S> Resource<S> where S: Clone + Send + Sync + 'static, { /// Create a `Resource` with the given name. /// /// All routes will be nested at `/{resource_name}`. pub fn named(resource_name: &str) -> Self { Self { name: resource_name.to_owned(), router: Router::new(), } } /// Add a handler at `GET /{resource_name}`. pub fn index<H, T>(self, handler: H) -> Self where H: Handler<T, S>, T: 'static, { let path = self.index_create_path(); self.route(&path, get(handler)) } /// Add a handler at `POST /{resource_name}`. pub fn create<H, T>(self, handler: H) -> Self where H: Handler<T, S>, T: 'static, { let path = self.index_create_path(); self.route(&path, post(handler)) } /// Add a handler at `GET /{resource_name}/new`. pub fn new<H, T>(self, handler: H) -> Self where H: Handler<T, S>, T: 'static, { let path = format!("/{}/new", self.name); self.route(&path, get(handler)) } /// Add a handler at `GET /<resource_name>/{<resource_name>_id}`. /// /// For example when the resources are posts: `GET /post/{post_id}`. pub fn show<H, T>(self, handler: H) -> Self where H: Handler<T, S>, T: 'static, { let path = self.show_update_destroy_path(); self.route(&path, get(handler)) } /// Add a handler at `GET /<resource_name>/{<resource_name>_id}/edit`. /// /// For example when the resources are posts: `GET /post/{post_id}/edit`. pub fn edit<H, T>(self, handler: H) -> Self where H: Handler<T, S>, T: 'static, { let path = format!("/{0}/{{{0}_id}}/edit", self.name); self.route(&path, get(handler)) } /// Add a handler at `PUT or PATCH /<resource_name>/{<resource_name>_id}`. /// /// For example when the resources are posts: `PUT /post/{post_id}`. pub fn update<H, T>(self, handler: H) -> Self where H: Handler<T, S>, T: 'static, { let path = self.show_update_destroy_path(); self.route( &path, on(MethodFilter::PUT.or(MethodFilter::PATCH), handler), ) } /// Add a handler at `DELETE /<resource_name>/{<resource_name>_id}`. /// /// For example when the resources are posts: `DELETE /post/{post_id}`. pub fn destroy<H, T>(self, handler: H) -> Self where H: Handler<T, S>, T: 'static, { let path = self.show_update_destroy_path(); self.route(&path, delete(handler)) } fn index_create_path(&self) -> String { format!("/{}", self.name) } fn show_update_destroy_path(&self) -> String { format!("/{0}/{{{0}_id}}", self.name) } fn route(mut self, path: &str, method_router: MethodRouter<S>) -> Self { self.router = self.router.route(path, method_router); self } } impl<S> From<Resource<S>> for Router<S> { fn from(resource: Resource<S>) -> Self { resource.router } } #[cfg(test)] mod tests { #[allow(unused_imports)] use super::*; use axum::{body::Body, extract::Path, http::Method}; use http::Request; use http_body_util::BodyExt; use tower::ServiceExt; #[tokio::test] async fn works() { let users = Resource::named("users") .index(|| async { "users#index" }) .create(|| async { "users#create" }) .new(|| async { "users#new" }) .show(|Path(id): Path<u64>| async move { format!("users#show id={id}") }) .edit(|Path(id): Path<u64>| async move { format!("users#edit id={id}") }) .update(|Path(id): Path<u64>| async move { format!("users#update id={id}") }) .destroy(|Path(id): Path<u64>| async move { format!("users#destroy id={id}") }); let app = Router::new().merge(users); assert_eq!(call_route(&app, Method::GET, "/users").await, "users#index"); assert_eq!( call_route(&app, Method::POST, "/users").await, "users#create" ); assert_eq!( call_route(&app, Method::GET, "/users/new").await, "users#new" ); assert_eq!( call_route(&app, Method::GET, "/users/1").await, "users#show id=1" ); assert_eq!( call_route(&app, Method::GET, "/users/1/edit").await, "users#edit id=1" ); assert_eq!( call_route(&app, Method::PATCH, "/users/1").await, "users#update id=1" ); assert_eq!( call_route(&app, Method::PUT, "/users/1").await, "users#update id=1" ); assert_eq!( call_route(&app, Method::DELETE, "/users/1").await, "users#destroy id=1" ); } async fn call_route(app: &Router, method: Method, uri: &str) -> String { let res = app .clone() .oneshot( Request::builder() .method(method) .uri(uri) .body(Body::empty()) .unwrap(), ) .await .unwrap(); let bytes = res.collect().await.unwrap().to_bytes(); String::from_utf8(bytes.to_vec()).unwrap() } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/routing/mod.rs
axum-extra/src/routing/mod.rs
//! Additional types for defining routes. use axum::{ extract::{OriginalUri, Request}, response::{IntoResponse, Redirect, Response}, routing::{any, on, MethodFilter, MethodRouter}, Router, }; use http::{uri::PathAndQuery, StatusCode, Uri}; use std::{borrow::Cow, convert::Infallible}; use tower_service::Service; mod resource; #[cfg(feature = "typed-routing")] mod typed; pub use self::resource::Resource; #[cfg(feature = "typed-routing")] pub use self::typed::WithQueryParams; #[cfg(feature = "typed-routing")] pub use axum_macros::TypedPath; #[cfg(feature = "typed-routing")] pub use self::typed::{SecondElementIs, TypedPath}; // Validates a path at compile time, used with the vpath macro. #[rustversion::since(1.80)] #[doc(hidden)] #[must_use] pub const fn __private_validate_static_path(path: &'static str) -> &'static str { if path.is_empty() { panic!("Paths must start with a `/`. Use \"/\" for root routes") } if path.as_bytes()[0] != b'/' { panic!("Paths must start with /"); } path } /// This macro aborts compilation if the path is invalid. /// /// This example will fail to compile: /// /// ```compile_fail /// use axum::routing::{Router, get}; /// use axum_extra::vpath; /// /// let router = axum::Router::<()>::new() /// .route(vpath!("invalid_path"), get(root)) /// .to_owned(); /// /// async fn root() {} /// ``` /// /// This one will compile without problems: /// /// ```no_run /// use axum::routing::{Router, get}; /// use axum_extra::vpath; /// /// let router = axum::Router::<()>::new() /// .route(vpath!("/valid_path"), get(root)) /// .to_owned(); /// /// async fn root() {} /// ``` /// /// This macro is available only on rust versions 1.80 and above. #[rustversion::since(1.80)] #[macro_export] macro_rules! vpath { ($e:expr) => { const { $crate::routing::__private_validate_static_path($e) } }; } /// Extension trait that adds additional methods to [`Router`]. #[allow(clippy::return_self_not_must_use)] pub trait RouterExt<S>: 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 /// implement [`TypedPath`]. /// /// See [`TypedPath`] for more details and examples. #[cfg(feature = "typed-routing")] fn typed_get<H, T, P>(self, handler: H) -> Self where H: axum::handler::Handler<T, S>, T: SecondElementIs<P> + 'static, P: TypedPath; /// Add a typed `DELETE` route to the router. /// /// The path will be inferred from the first argument to the handler function which must /// implement [`TypedPath`]. /// /// See [`TypedPath`] for more details and examples. #[cfg(feature = "typed-routing")] fn typed_delete<H, T, P>(self, handler: H) -> Self where H: axum::handler::Handler<T, S>, T: SecondElementIs<P> + 'static, P: TypedPath; /// Add a typed `HEAD` route to the router. /// /// The path will be inferred from the first argument to the handler function which must /// implement [`TypedPath`]. /// /// See [`TypedPath`] for more details and examples. #[cfg(feature = "typed-routing")] fn typed_head<H, T, P>(self, handler: H) -> Self where H: axum::handler::Handler<T, S>, T: SecondElementIs<P> + 'static, P: TypedPath; /// Add a typed `OPTIONS` route to the router. /// /// The path will be inferred from the first argument to the handler function which must /// implement [`TypedPath`]. /// /// See [`TypedPath`] for more details and examples. #[cfg(feature = "typed-routing")] fn typed_options<H, T, P>(self, handler: H) -> Self where H: axum::handler::Handler<T, S>, T: SecondElementIs<P> + 'static, P: TypedPath; /// Add a typed `PATCH` route to the router. /// /// The path will be inferred from the first argument to the handler function which must /// implement [`TypedPath`]. /// /// See [`TypedPath`] for more details and examples. #[cfg(feature = "typed-routing")] fn typed_patch<H, T, P>(self, handler: H) -> Self where H: axum::handler::Handler<T, S>, T: SecondElementIs<P> + 'static, P: TypedPath; /// Add a typed `POST` route to the router. /// /// The path will be inferred from the first argument to the handler function which must /// implement [`TypedPath`]. /// /// See [`TypedPath`] for more details and examples. #[cfg(feature = "typed-routing")] fn typed_post<H, T, P>(self, handler: H) -> Self where H: axum::handler::Handler<T, S>, T: SecondElementIs<P> + 'static, P: TypedPath; /// Add a typed `PUT` route to the router. /// /// The path will be inferred from the first argument to the handler function which must /// implement [`TypedPath`]. /// /// See [`TypedPath`] for more details and examples. #[cfg(feature = "typed-routing")] fn typed_put<H, T, P>(self, handler: H) -> Self where H: axum::handler::Handler<T, S>, T: SecondElementIs<P> + 'static, P: TypedPath; /// Add a typed `TRACE` route to the router. /// /// The path will be inferred from the first argument to the handler function which must /// implement [`TypedPath`]. /// /// See [`TypedPath`] for more details and examples. #[cfg(feature = "typed-routing")] fn typed_trace<H, T, P>(self, handler: H) -> Self where H: axum::handler::Handler<T, S>, T: SecondElementIs<P> + 'static, P: TypedPath; /// Add a typed `CONNECT` route to the router. /// /// The path will be inferred from the first argument to the handler function which must /// implement [`TypedPath`]. /// /// See [`TypedPath`] for more details and examples. #[cfg(feature = "typed-routing")] fn typed_connect<H, T, P>(self, handler: H) -> Self where H: axum::handler::Handler<T, S>, T: SecondElementIs<P> + 'static, P: TypedPath; /// Add another route to the router with an additional "trailing slash redirect" route. /// /// If you add a route _without_ a trailing slash, such as `/foo`, this method will also add a /// route for `/foo/` that redirects to `/foo`. /// /// If you add a route _with_ a trailing slash, such as `/bar/`, this method will also add a /// route for `/bar` that redirects to `/bar/`. /// /// This is similar to what axum 0.5.x did by default, except this explicitly adds another /// route, so trying to add a `/foo/` route after calling `.route_with_tsr("/foo", /* ... */)` /// will result in a panic due to route overlap. /// /// # Example /// /// ``` /// use axum::{Router, routing::get}; /// use axum_extra::routing::RouterExt; /// /// let app = Router::new() /// // `/foo/` will redirect to `/foo` /// .route_with_tsr("/foo", get(|| async {})) /// // `/bar` will redirect to `/bar/` /// .route_with_tsr("/bar/", get(|| async {})); /// # let _: Router = app; /// ``` fn route_with_tsr(self, path: &str, method_router: MethodRouter<S>) -> Self where Self: Sized; /// Add another route to the router with an additional "trailing slash redirect" route. /// /// This works like [`RouterExt::route_with_tsr`] but accepts any [`Service`]. fn route_service_with_tsr<T>(self, path: &str, service: T) -> Self where T: Service<Request, Error = Infallible> + Clone + Send + Sync + 'static, T::Response: IntoResponse, T::Future: Send + 'static, Self: Sized; } impl<S> RouterExt<S> for Router<S> where S: Clone + Send + Sync + 'static, { #[cfg(feature = "typed-routing")] fn typed_get<H, T, P>(self, handler: H) -> Self where H: axum::handler::Handler<T, S>, T: SecondElementIs<P> + 'static, P: TypedPath, { self.route(P::PATH, axum::routing::get(handler)) } #[cfg(feature = "typed-routing")] fn typed_delete<H, T, P>(self, handler: H) -> Self where H: axum::handler::Handler<T, S>, T: SecondElementIs<P> + 'static, P: TypedPath, { self.route(P::PATH, axum::routing::delete(handler)) } #[cfg(feature = "typed-routing")] fn typed_head<H, T, P>(self, handler: H) -> Self where H: axum::handler::Handler<T, S>, T: SecondElementIs<P> + 'static, P: TypedPath, { self.route(P::PATH, axum::routing::head(handler)) } #[cfg(feature = "typed-routing")] fn typed_options<H, T, P>(self, handler: H) -> Self where H: axum::handler::Handler<T, S>, T: SecondElementIs<P> + 'static, P: TypedPath, { self.route(P::PATH, axum::routing::options(handler)) } #[cfg(feature = "typed-routing")] fn typed_patch<H, T, P>(self, handler: H) -> Self where H: axum::handler::Handler<T, S>, T: SecondElementIs<P> + 'static, P: TypedPath, { self.route(P::PATH, axum::routing::patch(handler)) } #[cfg(feature = "typed-routing")] fn typed_post<H, T, P>(self, handler: H) -> Self where H: axum::handler::Handler<T, S>, T: SecondElementIs<P> + 'static, P: TypedPath, { self.route(P::PATH, axum::routing::post(handler)) } #[cfg(feature = "typed-routing")] fn typed_put<H, T, P>(self, handler: H) -> Self where H: axum::handler::Handler<T, S>, T: SecondElementIs<P> + 'static, P: TypedPath, { self.route(P::PATH, axum::routing::put(handler)) } #[cfg(feature = "typed-routing")] fn typed_trace<H, T, P>(self, handler: H) -> Self where H: axum::handler::Handler<T, S>, T: SecondElementIs<P> + 'static, P: TypedPath, { self.route(P::PATH, axum::routing::trace(handler)) } #[cfg(feature = "typed-routing")] fn typed_connect<H, T, P>(self, handler: H) -> Self where H: axum::handler::Handler<T, S>, T: SecondElementIs<P> + 'static, P: TypedPath, { self.route(P::PATH, axum::routing::connect(handler)) } #[track_caller] fn route_with_tsr(mut self, path: &str, method_router: MethodRouter<S>) -> Self where Self: Sized, { validate_tsr_path(path); let method_filter = method_router.method_filter(); self = self.route(path, method_router); add_tsr_redirect_route(self, path, method_filter) } #[track_caller] fn route_service_with_tsr<T>(mut self, path: &str, service: T) -> Self where T: Service<Request, Error = Infallible> + Clone + Send + Sync + 'static, T::Response: IntoResponse, T::Future: Send + 'static, Self: Sized, { validate_tsr_path(path); self = self.route_service(path, service); add_tsr_redirect_route(self, path, None) } } #[track_caller] fn validate_tsr_path(path: &str) { if path == "/" { panic!("Cannot add a trailing slash redirect route for `/`") } } fn add_tsr_redirect_route<S>( router: Router<S>, path: &str, method_filter: Option<MethodFilter>, ) -> Router<S> where S: Clone + Send + Sync + 'static, { async fn redirect_handler(OriginalUri(uri): OriginalUri) -> Response { let new_uri = map_path(uri, |path| { path.strip_suffix('/') .map(Cow::Borrowed) .unwrap_or_else(|| Cow::Owned(format!("{path}/"))) }); if let Some(new_uri) = new_uri { Redirect::permanent(&new_uri.to_string()).into_response() } else { StatusCode::BAD_REQUEST.into_response() } } let _slot; let redirect_path = if let Some(without_slash) = path.strip_suffix('/') { without_slash } else { // FIXME: Can return `&format!(...)` directly when MSRV is updated _slot = format!("{path}/"); &_slot }; let method_router = match method_filter { Some(f) => on(f, redirect_handler), None => any(redirect_handler), }; router.route(redirect_path, method_router) } /// Map the path of a `Uri`. /// /// Returns `None` if the `Uri` cannot be put back together with the new path. fn map_path<F>(original_uri: Uri, f: F) -> Option<Uri> where F: FnOnce(&str) -> Cow<'_, str>, { let mut parts = original_uri.into_parts(); let path_and_query = parts.path_and_query.as_ref()?; let new_path = f(path_and_query.path()); let new_path_and_query = if let Some(query) = &path_and_query.query() { format!("{new_path}?{query}").parse::<PathAndQuery>().ok()? } else { new_path.parse::<PathAndQuery>().ok()? }; parts.path_and_query = Some(new_path_and_query); Uri::from_parts(parts).ok() } mod sealed { pub trait Sealed {} impl<S> Sealed for axum::Router<S> {} } #[cfg(test)] mod tests { use super::*; use crate::test_helpers::*; use axum::{ extract::Path, routing::{get, post}, }; #[tokio::test] async fn test_tsr() { let app = Router::new() .route_with_tsr("/foo", get(|| async {})) .route_with_tsr("/bar/", get(|| async {})); let client = TestClient::new(app); let res = client.get("/foo").await; assert_eq!(res.status(), StatusCode::OK); let res = client.get("/foo/").await; assert_eq!(res.status(), StatusCode::PERMANENT_REDIRECT); assert_eq!(res.headers()["location"], "/foo"); let res = client.get("/bar/").await; assert_eq!(res.status(), StatusCode::OK); let res = client.get("/bar").await; assert_eq!(res.status(), StatusCode::PERMANENT_REDIRECT); assert_eq!(res.headers()["location"], "/bar/"); } #[tokio::test] async fn tsr_with_params() { let app = Router::new() .route_with_tsr( "/a/{a}", get(|Path(param): Path<String>| async move { param }), ) .route_with_tsr( "/b/{b}/", get(|Path(param): Path<String>| async move { param }), ); let client = TestClient::new(app); let res = client.get("/a/foo").await; assert_eq!(res.status(), StatusCode::OK); assert_eq!(res.text().await, "foo"); let res = client.get("/a/foo/").await; assert_eq!(res.status(), StatusCode::PERMANENT_REDIRECT); assert_eq!(res.headers()["location"], "/a/foo"); let res = client.get("/b/foo/").await; assert_eq!(res.status(), StatusCode::OK); assert_eq!(res.text().await, "foo"); let res = client.get("/b/foo").await; assert_eq!(res.status(), StatusCode::PERMANENT_REDIRECT); assert_eq!(res.headers()["location"], "/b/foo/"); } #[tokio::test] async fn tsr_maintains_query_params() { let app = Router::new().route_with_tsr("/foo", get(|| async {})); let client = TestClient::new(app); let res = client.get("/foo/?a=a").await; assert_eq!(res.status(), StatusCode::PERMANENT_REDIRECT); assert_eq!(res.headers()["location"], "/foo?a=a"); } #[tokio::test] async fn tsr_works_in_nested_router() { let app = Router::new().nest( "/neko", Router::new().route_with_tsr("/nyan/", get(|| async {})), ); let client = TestClient::new(app); let res = client.get("/neko/nyan/").await; assert_eq!(res.status(), StatusCode::OK); let res = client.get("/neko/nyan").await; assert_eq!(res.status(), StatusCode::PERMANENT_REDIRECT); assert_eq!(res.headers()["location"], "/neko/nyan/"); } #[test] fn tsr_independent_route_registration() { let _: Router = Router::new() .route_with_tsr("/x", get(|| async {})) .route_with_tsr("/x", post(|| async {})); } #[test] #[should_panic = "Cannot add a trailing slash redirect route for `/`"] fn tsr_at_root() { let _: Router = Router::new().route_with_tsr("/", get(|| async move {})); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/routing/typed.rs
axum-extra/src/routing/typed.rs
use std::{any::type_name, fmt}; use super::sealed::Sealed; use http::Uri; use serde_core::Serialize; /// A type safe path. /// /// This is used to statically connect a path to its corresponding handler using /// [`RouterExt::typed_get`], [`RouterExt::typed_post`], etc. /// /// # Example /// /// ```rust /// use serde::Deserialize; /// use axum::{Router, extract::Json}; /// use axum_extra::routing::{ /// TypedPath, /// RouterExt, // for `Router::typed_*` /// }; /// /// // A type safe route with `/users/{id}` as its associated path. /// #[derive(TypedPath, Deserialize)] /// #[typed_path("/users/{id}")] /// struct UsersMember { /// id: u32, /// } /// /// // A regular handler function that takes `UsersMember` as the first argument /// // and thus creates a typed connection between this handler and the `/users/{id}` path. /// // /// // The `TypedPath` must be the first argument to the function. /// async fn users_show( /// UsersMember { id }: UsersMember, /// ) { /// // ... /// } /// /// let app = Router::new() /// // Add our typed route to the router. /// // /// // The path will be inferred to `/users/{id}` since `users_show`'s /// // first argument is `UsersMember` which implements `TypedPath` /// .typed_get(users_show) /// .typed_post(users_create) /// .typed_delete(users_destroy); /// /// #[derive(TypedPath)] /// #[typed_path("/users")] /// struct UsersCollection; /// /// #[derive(Deserialize)] /// struct UsersCreatePayload { /* ... */ } /// /// async fn users_create( /// _: UsersCollection, /// // Our handlers can accept other extractors. /// Json(payload): Json<UsersCreatePayload>, /// ) { /// // ... /// } /// /// async fn users_destroy(_: UsersCollection) { /* ... */ } /// /// # /// # let app: Router = app; /// ``` /// /// # Using `#[derive(TypedPath)]` /// /// While `TypedPath` can be implemented manually, it's _highly_ recommended to derive it: /// /// ``` /// use serde::Deserialize; /// use axum_extra::routing::TypedPath; /// /// #[derive(TypedPath, Deserialize)] /// #[typed_path("/users/{id}")] /// struct UsersMember { /// id: u32, /// } /// ``` /// /// The macro expands to: /// /// - A `TypedPath` implementation. /// - A [`FromRequest`] implementation compatible with [`RouterExt::typed_get`], /// [`RouterExt::typed_post`], etc. This implementation uses [`Path`] and thus your struct must /// also implement [`serde::Deserialize`], unless it's a unit struct. /// - A [`Display`] implementation that interpolates the captures. This can be used to, among other /// things, create links to known paths and have them verified statically. Note that the /// [`Display`] implementation for each field must return something that's compatible with its /// [`Deserialize`] implementation. /// /// Additionally the macro will verify the captures in the path matches the fields of the struct. /// For example this fails to compile since the struct doesn't have a `team_id` field: /// /// ```compile_fail /// use serde::Deserialize; /// use axum_extra::routing::TypedPath; /// /// #[derive(TypedPath, Deserialize)] /// #[typed_path("/users/{id}/teams/{team_id}")] /// struct UsersMember { /// id: u32, /// } /// ``` /// /// Unit and tuple structs are also supported: /// /// ``` /// use serde::Deserialize; /// use axum_extra::routing::TypedPath; /// /// #[derive(TypedPath)] /// #[typed_path("/users")] /// struct UsersCollection; /// /// #[derive(TypedPath, Deserialize)] /// #[typed_path("/users/{id}")] /// struct UsersMember(u32); /// ``` /// /// ## Percent encoding /// /// The generated [`Display`] implementation will automatically percent-encode the arguments: /// /// ``` /// use serde::Deserialize; /// use axum_extra::routing::TypedPath; /// /// #[derive(TypedPath, Deserialize)] /// #[typed_path("/users/{id}")] /// struct UsersMember { /// id: String, /// } /// /// assert_eq!( /// UsersMember { /// id: "foo bar".to_string(), /// }.to_string(), /// "/users/foo%20bar", /// ); /// ``` /// /// ## Customizing the rejection /// /// By default the rejection used in the [`FromRequest`] implementation will be [`PathRejection`]. /// /// That can be customized using `#[typed_path("...", rejection(YourType))]`: /// /// ``` /// use serde::Deserialize; /// use axum_extra::routing::TypedPath; /// use axum::{ /// response::{IntoResponse, Response}, /// extract::rejection::PathRejection, /// }; /// /// #[derive(TypedPath, Deserialize)] /// #[typed_path("/users/{id}", rejection(UsersMemberRejection))] /// struct UsersMember { /// id: String, /// } /// /// struct UsersMemberRejection; /// /// // Your rejection type must implement `From<PathRejection>`. /// // /// // Here you can grab whatever details from the inner rejection /// // that you need. /// impl From<PathRejection> for UsersMemberRejection { /// fn from(rejection: PathRejection) -> Self { /// # UsersMemberRejection /// // ... /// } /// } /// /// // Your rejection must implement `IntoResponse`, like all rejections. /// impl IntoResponse for UsersMemberRejection { /// fn into_response(self) -> Response { /// # ().into_response() /// // ... /// } /// } /// ``` /// /// The `From<PathRejection>` requirement only applies if your typed path is a struct with named /// fields or a tuple struct. For unit structs your rejection type must implement `Default`: /// /// ``` /// use axum_extra::routing::TypedPath; /// use axum::response::{IntoResponse, Response}; /// /// #[derive(TypedPath)] /// #[typed_path("/users", rejection(UsersCollectionRejection))] /// struct UsersCollection; /// /// #[derive(Default)] /// struct UsersCollectionRejection; /// /// impl IntoResponse for UsersCollectionRejection { /// fn into_response(self) -> Response { /// # ().into_response() /// // ... /// } /// } /// ``` /// /// [`FromRequest`]: axum::extract::FromRequest /// [`RouterExt::typed_get`]: super::RouterExt::typed_get /// [`RouterExt::typed_post`]: super::RouterExt::typed_post /// [`Path`]: axum::extract::Path /// [`Display`]: std::fmt::Display /// [`Deserialize`]: serde::Deserialize /// [`PathRejection`]: axum::extract::rejection::PathRejection pub trait TypedPath: std::fmt::Display { /// The path with optional captures such as `/users/{id}`. const PATH: &'static str; /// Convert the path into a `Uri`. /// /// # Panics /// /// The default implementation parses the required [`Display`] implementation. If that fails it /// will panic. /// /// Using `#[derive(TypedPath)]` will never result in a panic since it percent-encodes /// arguments. /// /// [`Display`]: std::fmt::Display fn to_uri(&self) -> Uri { self.to_string().parse().unwrap() } /// Add query parameters to a path. /// /// # Example /// /// ``` /// use axum_extra::routing::TypedPath; /// use serde::Serialize; /// /// #[derive(TypedPath)] /// #[typed_path("/users")] /// struct Users; /// /// #[derive(Serialize)] /// struct Pagination { /// page: u32, /// per_page: u32, /// } /// /// let path = Users.with_query_params(Pagination { /// page: 1, /// per_page: 10, /// }); /// /// assert_eq!(path.to_uri(), "/users?&page=1&per_page=10"); /// ``` /// /// # Panics /// /// If `params` doesn't support being serialized as query params [`WithQueryParams`]'s [`Display`] /// implementation will panic, and thus [`WithQueryParams::to_uri`] will also panic. /// /// [`WithQueryParams::to_uri`]: TypedPath::to_uri /// [`Display`]: std::fmt::Display fn with_query_params<T>(self, params: T) -> WithQueryParams<Self, T> where T: Serialize, Self: Sized, { WithQueryParams { path: self, params } } } /// A [`TypedPath`] with query params. /// /// See [`TypedPath::with_query_params`] for more details. #[derive(Debug, Clone, Copy)] pub struct WithQueryParams<P, T> { path: P, params: T, } impl<P, T> fmt::Display for WithQueryParams<P, T> where P: TypedPath, T: Serialize, { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut out = self.path.to_string(); if !out.contains('?') { out.push('?'); } let mut urlencoder = form_urlencoded::Serializer::new(&mut out); self.params .serialize(serde_html_form::ser::Serializer::new(&mut urlencoder)) .unwrap_or_else(|err| { panic!( "failed to URL encode value of type `{}`: {err}", type_name::<T>(), ) }); f.write_str(&out)?; Ok(()) } } impl<P, T> TypedPath for WithQueryParams<P, T> where P: TypedPath, T: Serialize, { const PATH: &'static str = P::PATH; } /// Utility trait used with [`RouterExt`] to ensure the second element of a tuple type is a /// given type. /// /// If you see it in type errors it's most likely because the first argument to your handler doesn't /// implement [`TypedPath`]. /// /// You normally shouldn't have to use this trait directly. /// /// It is sealed such that it cannot be implemented outside this crate. /// /// [`RouterExt`]: super::RouterExt pub trait SecondElementIs<P>: Sealed {} macro_rules! impl_second_element_is { ( $($ty:ident),* $(,)? ) => { impl<M, P, $($ty,)*> SecondElementIs<P> for (M, P, $($ty,)*) where P: TypedPath {} impl<M, P, $($ty,)*> Sealed for (M, P, $($ty,)*) where P: TypedPath {} impl<M, P, $($ty,)*> SecondElementIs<P> for (M, Option<P>, $($ty,)*) where P: TypedPath {} impl<M, P, $($ty,)*> Sealed for (M, Option<P>, $($ty,)*) where P: TypedPath {} impl<M, P, E, $($ty,)*> SecondElementIs<P> for (M, Result<P, E>, $($ty,)*) where P: TypedPath {} impl<M, P, E, $($ty,)*> Sealed for (M, Result<P, E>, $($ty,)*) where P: TypedPath {} }; } impl_second_element_is!(); impl_second_element_is!(T1); impl_second_element_is!(T1, T2); impl_second_element_is!(T1, T2, T3); impl_second_element_is!(T1, T2, T3, T4); impl_second_element_is!(T1, T2, T3, T4, T5); impl_second_element_is!(T1, T2, T3, T4, T5, T6); impl_second_element_is!(T1, T2, T3, T4, T5, T6, T7); impl_second_element_is!(T1, T2, T3, T4, T5, T6, T7, T8); impl_second_element_is!(T1, T2, T3, T4, T5, T6, T7, T8, T9); impl_second_element_is!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10); impl_second_element_is!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11); impl_second_element_is!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12); impl_second_element_is!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13); impl_second_element_is!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14); impl_second_element_is!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15); impl_second_element_is!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16); #[cfg(test)] mod tests { use crate::routing::TypedPath; use serde::{Deserialize, Serialize}; #[derive(TypedPath, Deserialize)] #[typed_path("/users/{id}")] struct UsersShow { id: i32, } #[derive(Serialize)] struct Params { foo: &'static str, bar: i32, baz: bool, } #[test] fn with_params() { let path = UsersShow { id: 1 }.with_query_params(Params { foo: "foo", bar: 123, baz: true, }); let uri = path.to_uri(); // according to [the spec] starting the params with `?&` is allowed specifically: // // > If bytes is the empty byte sequence, then continue. // // [the spec]: https://url.spec.whatwg.org/#urlencoded-parsing assert_eq!(uri, "/users/1?&foo=foo&bar=123&baz=true"); } #[test] fn with_params_called_multiple_times() { let path = UsersShow { id: 1 } .with_query_params(Params { foo: "foo", bar: 123, baz: true, }) .with_query_params([("qux", 1337)]); let uri = path.to_uri(); assert_eq!(uri, "/users/1?&foo=foo&bar=123&baz=true&qux=1337"); } #[cfg(feature = "with-rejection")] #[allow(dead_code)] // just needs to compile fn supports_with_rejection() { use crate::routing::RouterExt; use axum::{ extract::rejection::PathRejection, response::{IntoResponse, Response}, Router, }; async fn handler(_: crate::extract::WithRejection<UsersShow, MyRejection>) {} struct MyRejection {} impl IntoResponse for MyRejection { fn into_response(self) -> Response { unimplemented!() } } impl From<PathRejection> for MyRejection { fn from(_: PathRejection) -> Self { unimplemented!() } } let _: Router = Router::new().typed_get(handler); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/body/async_read_body.rs
axum-extra/src/body/async_read_body.rs
use axum_core::{ body::Body, response::{IntoResponse, Response}, Error, }; use bytes::Bytes; use http_body::Body as HttpBody; use pin_project_lite::pin_project; use std::{ pin::Pin, task::{Context, Poll}, }; use tokio::io::AsyncRead; use tokio_util::io::ReaderStream; pin_project! { /// An [`HttpBody`] created from an [`AsyncRead`]. /// /// # Example /// /// `AsyncReadBody` can be used to stream the contents of a file: /// /// ```rust /// use axum::{ /// Router, /// routing::get, /// http::{StatusCode, header::CONTENT_TYPE}, /// response::{Response, IntoResponse}, /// }; /// use axum_extra::body::AsyncReadBody; /// use tokio::fs::File; /// /// async fn cargo_toml() -> Result<Response, (StatusCode, String)> { /// let file = File::open("Cargo.toml") /// .await /// .map_err(|err| { /// (StatusCode::NOT_FOUND, format!("File not found: {err}")) /// })?; /// /// let headers = [(CONTENT_TYPE, "text/x-toml")]; /// let body = AsyncReadBody::new(file); /// Ok((headers, body).into_response()) /// } /// /// let app = Router::new().route("/Cargo.toml", get(cargo_toml)); /// # let _: Router = app; /// ``` #[cfg(feature = "async-read-body")] #[derive(Debug)] #[must_use] pub struct AsyncReadBody { #[pin] body: Body, } } impl AsyncReadBody { /// Create a new `AsyncReadBody`. pub fn new<R>(read: R) -> Self where R: AsyncRead + Send + 'static, { Self { body: Body::from_stream(ReaderStream::new(read)), } } } impl HttpBody for AsyncReadBody { type Data = Bytes; type Error = Error; #[inline] fn poll_frame( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Option<Result<http_body::Frame<Self::Data>, Self::Error>>> { self.project().body.poll_frame(cx) } #[inline] fn is_end_stream(&self) -> bool { self.body.is_end_stream() } #[inline] fn size_hint(&self) -> http_body::SizeHint { self.body.size_hint() } } impl IntoResponse for AsyncReadBody { fn into_response(self) -> Response { self.body.into_response() } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/body/mod.rs
axum-extra/src/body/mod.rs
//! Additional bodies. #[cfg(feature = "async-read-body")] mod async_read_body; #[cfg(feature = "async-read-body")] pub use self::async_read_body::AsyncReadBody;
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/handler/or.rs
axum-extra/src/handler/or.rs
use super::HandlerCallWithExtractors; use crate::either::Either; use axum::{ extract::{FromRequest, FromRequestParts, Request}, handler::Handler, response::{IntoResponse, Response}, }; use futures_core::future::BoxFuture; use futures_util::future::{Either as EitherFuture, FutureExt, Map}; use std::{future::Future, marker::PhantomData}; /// [`Handler`] that runs one [`Handler`] and if that rejects it'll fallback to another /// [`Handler`]. /// /// Created with [`HandlerCallWithExtractors::or`](super::HandlerCallWithExtractors::or). #[allow(missing_debug_implementations)] pub struct Or<L, R, Lt, Rt, S> { pub(super) lhs: L, pub(super) rhs: R, pub(super) _marker: PhantomData<fn() -> (Lt, Rt, S)>, } impl<S, L, R, Lt, Rt> HandlerCallWithExtractors<Either<Lt, Rt>, S> for Or<L, R, Lt, Rt, S> where L: HandlerCallWithExtractors<Lt, S> + Send + 'static, R: HandlerCallWithExtractors<Rt, S> + Send + 'static, Rt: Send + 'static, Lt: Send + 'static, { // this puts `futures_util` in our public API but that's fine in axum-extra type Future = EitherFuture< Map<L::Future, fn(<L::Future as Future>::Output) -> Response>, Map<R::Future, fn(<R::Future as Future>::Output) -> Response>, >; fn call( self, extractors: Either<Lt, Rt>, state: S, ) -> <Self as HandlerCallWithExtractors<Either<Lt, Rt>, S>>::Future { match extractors { Either::E1(lt) => self .lhs .call(lt, state) .map(IntoResponse::into_response as _) .left_future(), Either::E2(rt) => self .rhs .call(rt, state) .map(IntoResponse::into_response as _) .right_future(), } } } impl<S, L, R, Lt, Rt, M> Handler<(M, Lt, Rt), S> for Or<L, R, Lt, Rt, S> where L: HandlerCallWithExtractors<Lt, S> + Clone + Send + Sync + 'static, R: HandlerCallWithExtractors<Rt, S> + Clone + Send + Sync + 'static, Lt: FromRequestParts<S> + Send + 'static, Rt: FromRequest<S, M> + Send + 'static, Lt::Rejection: Send, Rt::Rejection: Send, S: Send + Sync + 'static, { // this puts `futures_util` in our public API but that's fine in axum-extra type Future = BoxFuture<'static, Response>; fn call(self, req: Request, state: S) -> Self::Future { let (mut parts, body) = req.into_parts(); Box::pin(async move { if let Ok(lt) = Lt::from_request_parts(&mut parts, &state).await { return self.lhs.call(lt, state).await; } let req = Request::from_parts(parts, body); match Rt::from_request(req, &state).await { Ok(rt) => self.rhs.call(rt, state).await, Err(rejection) => rejection.into_response(), } }) } } impl<L, R, Lt, Rt, S> Copy for Or<L, R, Lt, Rt, S> where L: Copy, R: Copy, { } impl<L, R, Lt, Rt, S> Clone for Or<L, R, Lt, Rt, S> where L: Clone, R: Clone, { fn clone(&self) -> Self { Self { lhs: self.lhs.clone(), rhs: self.rhs.clone(), _marker: self._marker, } } } #[cfg(test)] mod tests { use super::*; use crate::test_helpers::*; use axum::{ extract::{Path, Query}, routing::get, Router, }; use serde::Deserialize; #[tokio::test] async fn works() { #[derive(Deserialize)] struct Params { a: String, } async fn one(Path(id): Path<u32>) -> String { id.to_string() } async fn two(Query(params): Query<Params>) -> String { params.a } async fn three() -> &'static str { "fallback" } let app = Router::new().route("/{id}", get(one.or(two).or(three))); let client = TestClient::new(app); let res = client.get("/123").await; assert_eq!(res.text().await, "123"); let res = client.get("/foo?a=bar").await; assert_eq!(res.text().await, "bar"); let res = client.get("/foo").await; assert_eq!(res.text().await, "fallback"); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/handler/mod.rs
axum-extra/src/handler/mod.rs
//! Additional handler utilities. use axum::body::Body; use axum::extract::Request; use axum::{ extract::FromRequest, handler::Handler, response::{IntoResponse, Response}, }; use futures_core::future::BoxFuture; use futures_util::future::{FutureExt, Map}; use std::{future::Future, marker::PhantomData}; mod or; pub use self::or::Or; /// Trait for async functions that can be used to handle requests. /// /// This trait is similar to [`Handler`] but rather than taking the request it takes the extracted /// inputs. /// /// The drawbacks of this trait is that you cannot apply middleware to individual handlers like you /// can with [`Handler::layer`]. pub trait HandlerCallWithExtractors<T, S>: Sized { /// The type of future calling this handler returns. type Future: Future<Output = Response> + Send + 'static; /// Call the handler with the extracted inputs. fn call(self, extractors: T, state: S) -> <Self as HandlerCallWithExtractors<T, S>>::Future; /// Convert this `HandlerCallWithExtractors` into [`Handler`]. fn into_handler(self) -> IntoHandler<Self, T, S> { IntoHandler { handler: self, _marker: PhantomData, } } /// Chain two handlers together, running the second one if the first one rejects. /// /// Note that this only moves to the next handler if an extractor fails. The response from /// handlers are not considered. /// /// # Example /// /// ``` /// use axum_extra::handler::HandlerCallWithExtractors; /// use axum::{ /// Router, /// routing::get, /// extract::FromRequestParts, /// }; /// /// // handlers for varying levels of access /// async fn admin(admin: AdminPermissions) { /// // request came from an admin /// } /// /// async fn user(user: User) { /// // we have a `User` /// } /// /// async fn guest() { /// // `AdminPermissions` and `User` failed, so we're just a guest /// } /// /// // extractors for checking permissions /// struct AdminPermissions {} /// /// impl<S> FromRequestParts<S> for AdminPermissions /// where /// S: Send + Sync, /// { /// // check for admin permissions... /// # type Rejection = (); /// # async fn from_request_parts(parts: &mut http::request::Parts, state: &S) -> Result<Self, Self::Rejection> { /// # todo!() /// # } /// } /// /// struct User {} /// /// impl<S> FromRequestParts<S> for User /// where /// S: Send + Sync, /// { /// // check for a logged in user... /// # type Rejection = (); /// # async fn from_request_parts(parts: &mut http::request::Parts, state: &S) -> Result<Self, Self::Rejection> { /// # todo!() /// # } /// } /// /// let app = Router::new().route( /// "/users/{id}", /// get( /// // first try `admin`, if that rejects run `user`, finally falling back /// // to `guest` /// admin.or(user).or(guest) /// ) /// ); /// # let _: Router = app; /// ``` fn or<R, Rt>(self, rhs: R) -> Or<Self, R, T, Rt, S> where R: HandlerCallWithExtractors<Rt, S>, { Or { lhs: self, rhs, _marker: PhantomData, } } } macro_rules! impl_handler_call_with { ( $($ty:ident),* $(,)? ) => { #[allow(non_snake_case)] impl<F, Fut, S, $($ty,)*> HandlerCallWithExtractors<($($ty,)*), S> for F where F: FnOnce($($ty,)*) -> Fut, Fut: Future + Send + 'static, Fut::Output: IntoResponse, { // this puts `futures_util` in our public API but that's fine in axum-extra type Future = Map<Fut, fn(Fut::Output) -> Response>; fn call( self, ($($ty,)*): ($($ty,)*), _state: S, ) -> <Self as HandlerCallWithExtractors<($($ty,)*), S>>::Future { self($($ty,)*).map(IntoResponse::into_response) } } }; } impl_handler_call_with!(); impl_handler_call_with!(T1); impl_handler_call_with!(T1, T2); impl_handler_call_with!(T1, T2, T3); impl_handler_call_with!(T1, T2, T3, T4); impl_handler_call_with!(T1, T2, T3, T4, T5); impl_handler_call_with!(T1, T2, T3, T4, T5, T6); impl_handler_call_with!(T1, T2, T3, T4, T5, T6, T7); impl_handler_call_with!(T1, T2, T3, T4, T5, T6, T7, T8); impl_handler_call_with!(T1, T2, T3, T4, T5, T6, T7, T8, T9); impl_handler_call_with!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10); impl_handler_call_with!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11); impl_handler_call_with!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12); impl_handler_call_with!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13); impl_handler_call_with!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14); impl_handler_call_with!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15); impl_handler_call_with!(T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16); /// A [`Handler`] created from a [`HandlerCallWithExtractors`]. /// /// Created with [`HandlerCallWithExtractors::into_handler`]. #[allow(missing_debug_implementations)] pub struct IntoHandler<H, T, S> { handler: H, _marker: PhantomData<fn() -> (T, S)>, } impl<H, T, S> Handler<T, S> for IntoHandler<H, T, S> where H: HandlerCallWithExtractors<T, S> + Clone + Send + Sync + 'static, T: FromRequest<S> + Send + 'static, T::Rejection: Send, S: Send + Sync + 'static, { type Future = BoxFuture<'static, Response>; 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, Err(rejection) => rejection.into_response(), } }) } } impl<H, T, S> Copy for IntoHandler<H, T, S> where H: Copy {} impl<H, T, S> Clone for IntoHandler<H, T, S> where H: Clone, { fn clone(&self) -> Self { Self { handler: self.handler.clone(), _marker: self._marker, } } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/response/multiple.rs
axum-extra/src/response/multiple.rs
//! Generate forms to use in responses. use axum_core::response::{IntoResponse, Response}; use fastrand; use http::{header, HeaderMap, StatusCode}; use mime::Mime; /// Create multipart forms to be used in API responses. /// /// This struct implements [`IntoResponse`], and so it can be returned from a handler. #[must_use] #[derive(Debug)] pub struct MultipartForm { parts: Vec<Part>, } impl MultipartForm { /// Initialize a new multipart form with the provided vector of parts. /// /// # Examples /// /// ```rust /// use axum_extra::response::multiple::{MultipartForm, Part}; /// /// let parts: Vec<Part> = vec![Part::text("foo".to_string(), "abc"), Part::text("bar".to_string(), "def")]; /// let form = MultipartForm::with_parts(parts); /// ``` pub fn with_parts(parts: Vec<Part>) -> Self { Self { parts } } } impl IntoResponse for MultipartForm { fn into_response(self) -> Response { // see RFC5758 for details let boundary = generate_boundary(); let mut headers = HeaderMap::new(); let mime_type: Mime = match format!("multipart/form-data; boundary={boundary}").parse() { Ok(m) => m, // Realistically this should never happen unless the boundary generation code // is modified, and that will be caught by unit tests Err(_) => { return ( StatusCode::INTERNAL_SERVER_ERROR, "Invalid multipart boundary generated", ) .into_response() } }; // The use of unwrap is safe here because mime types are inherently string representable headers.insert(header::CONTENT_TYPE, mime_type.to_string().parse().unwrap()); let mut serialized_form: Vec<u8> = Vec::new(); for part in self.parts { // for each part, the boundary is preceded by two dashes serialized_form.extend_from_slice(format!("--{boundary}\r\n").as_bytes()); serialized_form.extend_from_slice(&part.serialize()); } serialized_form.extend_from_slice(format!("--{boundary}--").as_bytes()); (headers, serialized_form).into_response() } } // Valid settings for that header are: "base64", "quoted-printable", "8bit", "7bit", and "binary". /// A single part of a multipart form as defined by /// <https://www.w3.org/TR/html401/interact/forms.html#h-17.13.4> /// and RFC5758. #[derive(Debug)] pub struct Part { // Every part is expected to contain: // - a [Content-Disposition](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition // header, where `Content-Disposition` is set to `form-data`, with a parameter of `name` that is set to // the name of the field in the form. In the below example, the name of the field is `user`: // ``` // Content-Disposition: form-data; name="user" // ``` // If the field contains a file, then the `filename` parameter may be set to the name of the file. // Handling for non-ascii field names is not done here, support for non-ascii characters may be encoded using // methodology described in RFC 2047. // - (optionally) a `Content-Type` header, which if not set, defaults to `text/plain`. // If the field contains a file, then the file should be identified with that file's MIME type (eg: `image/gif`). // If the `MIME` type is not known or specified, then the MIME type should be set to `application/octet-stream`. /// The name of the part in question name: String, /// If the part should be treated as a file, the filename that should be attached that part filename: Option<String>, /// The `Content-Type` header. While not strictly required, it is always set here mime_type: Mime, /// The content/body of the part contents: Vec<u8>, } impl Part { /// Create a new part with `Content-Type` of `text/plain` with the supplied name and contents. /// /// This form will not have a defined file name. /// /// # Examples /// /// ```rust /// use axum_extra::response::multiple::{MultipartForm, Part}; /// /// // create a form with a single part that has a field with a name of "foo", /// // and a value of "abc" /// let parts: Vec<Part> = vec![Part::text("foo".to_string(), "abc")]; /// let form = MultipartForm::from_iter(parts); /// ``` #[must_use] pub fn text(name: String, contents: &str) -> Self { Self { name, filename: None, mime_type: mime::TEXT_PLAIN_UTF_8, contents: contents.as_bytes().to_vec(), } } /// Create a new part containing a generic file, with a `Content-Type` of `application/octet-stream` /// using the provided file name, field name, and contents. /// /// If the MIME type of the file is known, consider using `Part::raw_part`. /// /// # Examples /// /// ```rust /// use axum_extra::response::multiple::{MultipartForm, Part}; /// /// // create a form with a single part that has a field with a name of "foo", /// // with a file name of "foo.txt", and with the specified contents /// let parts: Vec<Part> = vec![Part::file("foo", "foo.txt", vec![0x68, 0x68, 0x20, 0x6d, 0x6f, 0x6d])]; /// let form = MultipartForm::from_iter(parts); /// ``` #[must_use] pub fn file(field_name: &str, file_name: &str, contents: Vec<u8>) -> Self { Self { name: field_name.to_owned(), filename: Some(file_name.to_owned()), // If the `MIME` type is not known or specified, then the MIME type should be set to `application/octet-stream`. // See RFC2388 section 3 for specifics. mime_type: mime::APPLICATION_OCTET_STREAM, contents, } } /// Create a new part with more fine-grained control over the semantics of that part. /// /// The caller is assumed to have set a valid MIME type. /// /// This function will return an error if the provided MIME type is not valid. /// /// # Examples /// /// ```rust /// use axum_extra::response::multiple::{MultipartForm, Part}; /// /// // create a form with a single part that has a field with a name of "part_name", /// // with a MIME type of "application/json", and the supplied contents. /// let parts: Vec<Part> = vec![Part::raw_part("part_name", "application/json", vec![0x68, 0x68, 0x20, 0x6d, 0x6f, 0x6d], None).expect("MIME type must be valid")]; /// let form = MultipartForm::from_iter(parts); /// ``` pub fn raw_part( name: &str, mime_type: &str, contents: Vec<u8>, filename: Option<&str>, ) -> Result<Self, &'static str> { let mime_type = mime_type.parse().map_err(|_| "Invalid MIME type")?; Ok(Self { name: name.to_owned(), filename: filename.map(|f| f.to_owned()), mime_type, contents, }) } /// Serialize this part into a chunk that can be easily inserted into a larger form pub(super) fn serialize(&self) -> Vec<u8> { // A part is serialized in this general format: // // the filename is optional // Content-Disposition: form-data; name="FIELD_NAME"; filename="FILENAME"\r\n // // the mime type (not strictly required by the spec, but always sent here) // Content-Type: mime/type\r\n // // a blank line, then the contents of the file start // \r\n // CONTENTS\r\n // Format what we can as a string, then handle the rest at a byte level let mut serialized_part = format!("Content-Disposition: form-data; name=\"{}\"", self.name); // specify a filename if one was set if let Some(filename) = &self.filename { serialized_part += &format!("; filename=\"{filename}\""); } serialized_part += "\r\n"; // specify the MIME type serialized_part += &format!("Content-Type: {}\r\n", self.mime_type); serialized_part += "\r\n"; let mut part_bytes = serialized_part.as_bytes().to_vec(); part_bytes.extend_from_slice(&self.contents); part_bytes.extend_from_slice(b"\r\n"); part_bytes } } impl FromIterator<Part> for MultipartForm { fn from_iter<T: IntoIterator<Item = Part>>(iter: T) -> Self { Self { parts: iter.into_iter().collect(), } } } /// A boundary is defined as a user defined (arbitrary) value that does not occur in any of the data. /// /// Because the specification does not clearly define a methodology for generating boundaries, this implementation /// follow's Reqwest's, and generates a boundary in the format of `XXXXXXXX-XXXXXXXX-XXXXXXXX-XXXXXXXX` where `XXXXXXXX` /// is a hexadecimal representation of a pseudo randomly generated u64. fn generate_boundary() -> String { let a = fastrand::u64(0..u64::MAX); let b = fastrand::u64(0..u64::MAX); let c = fastrand::u64(0..u64::MAX); let d = fastrand::u64(0..u64::MAX); format!("{a:016x}-{b:016x}-{c:016x}-{d:016x}") } #[cfg(test)] mod tests { use super::{generate_boundary, MultipartForm, Part}; use axum::{body::Body, http}; use axum::{routing::get, Router}; use http::{Request, Response}; use http_body_util::BodyExt; use mime::Mime; use tower::ServiceExt; #[tokio::test] async fn process_form() -> Result<(), Box<dyn std::error::Error>> { // create a boilerplate handle that returns a form async fn handle() -> MultipartForm { let parts: Vec<Part> = vec![ Part::text("part1".to_owned(), "basictext"), Part::file( "part2", "file.txt", vec![0x68, 0x69, 0x20, 0x6d, 0x6f, 0x6d], ), Part::raw_part("part3", "text/plain", b"rawpart".to_vec(), None).unwrap(), ]; MultipartForm::from_iter(parts) } // make a request to that handle let app = Router::new().route("/", get(handle)); let response: Response<_> = app .oneshot(Request::builder().uri("/").body(Body::empty())?) .await?; // content_type header let ct_header = response.headers().get("content-type").unwrap().to_str()?; let boundary = ct_header.split("boundary=").nth(1).unwrap().to_owned(); let body: &[u8] = &response.into_body().collect().await?.to_bytes(); assert_eq!( std::str::from_utf8(body)?, format!( "--{boundary}\r\n\ Content-Disposition: form-data; name=\"part1\"\r\n\ Content-Type: text/plain; charset=utf-8\r\n\ \r\n\ basictext\r\n\ --{boundary}\r\n\ Content-Disposition: form-data; name=\"part2\"; filename=\"file.txt\"\r\n\ Content-Type: application/octet-stream\r\n\ \r\n\ hi mom\r\n\ --{boundary}\r\n\ Content-Disposition: form-data; name=\"part3\"\r\n\ Content-Type: text/plain\r\n\ \r\n\ rawpart\r\n\ --{boundary}--", ) ); Ok(()) } #[test] fn valid_boundary_generation() { for _ in 0..256 { let boundary = generate_boundary(); let mime_type: Result<Mime, _> = format!("multipart/form-data; boundary={boundary}").parse(); assert!( mime_type.is_ok(), "The generated boundary was unable to be parsed into a valid mime type." ); } } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/response/attachment.rs
axum-extra/src/response/attachment.rs
use axum_core::response::IntoResponse; use http::{header, HeaderMap, HeaderValue}; use tracing::error; /// A file attachment response. /// /// This type will set the `Content-Disposition` header to `attachment`. In response a webbrowser /// will offer to download the file instead of displaying it directly. /// /// Use the `filename` and `content_type` methods to set the filename or content-type of the /// attachment. If these values are not set they will not be sent. /// /// /// # Example /// /// ```rust /// use axum::{http::StatusCode, routing::get, Router}; /// use axum_extra::response::Attachment; /// /// async fn cargo_toml() -> Result<Attachment<String>, (StatusCode, String)> { /// let file_contents = tokio::fs::read_to_string("Cargo.toml") /// .await /// .map_err(|err| (StatusCode::NOT_FOUND, format!("File not found: {err}")))?; /// Ok(Attachment::new(file_contents) /// .filename("Cargo.toml") /// .content_type("text/x-toml")) /// } /// /// let app = Router::new().route("/Cargo.toml", get(cargo_toml)); /// let _: Router = app; /// ``` /// /// # Note /// /// If you use axum with hyper, hyper will set the `Content-Length` if it is known. #[derive(Debug)] #[must_use] pub struct Attachment<T> { inner: T, filename: Option<HeaderValue>, content_type: Option<HeaderValue>, } impl<T: IntoResponse> Attachment<T> { /// Creates a new [`Attachment`]. pub fn new(inner: T) -> Self { Self { inner, filename: None, content_type: None, } } /// Sets the filename of the [`Attachment`]. /// /// This updates the `Content-Disposition` header to add a filename. pub fn filename<H: TryInto<HeaderValue>>(mut self, value: H) -> Self { self.filename = if let Ok(filename) = value.try_into() { Some(filename) } else { error!("Attachment filename contains invalid characters"); None }; self } /// Sets the content-type of the [`Attachment`] pub fn content_type<H: TryInto<HeaderValue>>(mut self, value: H) -> Self { if let Ok(content_type) = value.try_into() { self.content_type = Some(content_type); } else { error!("Attachment content-type contains invalid characters"); } self } } impl<T> IntoResponse for Attachment<T> where T: IntoResponse, { fn into_response(self) -> axum_core::response::Response { let mut headers = HeaderMap::new(); if let Some(content_type) = self.content_type { headers.append(header::CONTENT_TYPE, content_type); } let content_disposition = if let Some(filename) = self.filename { let mut bytes = b"attachment; filename=\"".to_vec(); bytes.extend_from_slice(filename.as_bytes()); bytes.push(b'\"'); HeaderValue::from_bytes(&bytes).expect("This was a HeaderValue so this can not fail") } else { HeaderValue::from_static("attachment") }; headers.append(header::CONTENT_DISPOSITION, content_disposition); (headers, self.inner).into_response() } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/response/error_response.rs
axum-extra/src/response/error_response.rs
use axum_core::response::{IntoResponse, Response}; use http::StatusCode; use std::error::Error; use tracing::error; /// Convenience response to create an error response from a non-[`IntoResponse`] error /// /// This provides a method to quickly respond with an error that does not implement /// the `IntoResponse` trait itself. This type should only be used for debugging purposes or internal /// facing applications, as it includes the full error chain with descriptions, /// thus leaking information that could possibly be sensitive. /// /// ```rust /// use axum_extra::response::InternalServerError; /// use axum_core::response::IntoResponse; /// # use std::io::{Error, ErrorKind}; /// # fn try_thing() -> Result<(), Error> { /// # Err(Error::new(ErrorKind::Other, "error")) /// # } /// /// async fn maybe_error() -> Result<String, InternalServerError<Error>> { /// try_thing().map_err(InternalServerError)?; /// // do something on success /// # Ok(String::from("ok")) /// } /// ``` #[derive(Debug)] pub struct InternalServerError<T>(pub T); impl<T: Error + 'static> IntoResponse for InternalServerError<T> { fn into_response(self) -> Response { error!(error = &self.0 as &dyn Error); ( StatusCode::INTERNAL_SERVER_ERROR, "An error occurred while processing your request.", ) .into_response() } } #[cfg(test)] mod tests { use super::*; use std::io::Error; #[test] fn internal_server_error() { let response = InternalServerError(Error::other("Test")).into_response(); assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/response/erased_json.rs
axum-extra/src/response/erased_json.rs
use std::sync::Arc; use axum_core::response::{IntoResponse, Response}; use bytes::{BufMut, Bytes, BytesMut}; use http::{header, HeaderValue, StatusCode}; use serde_core::Serialize; /// A response type that holds a JSON in serialized form. /// /// This allows returning a borrowing type from a handler, or returning different response /// types as JSON from different branches inside a handler. /// /// Like [`axum::Json`], /// if the [`Serialize`] implementation fails /// or if a map with non-string keys is used, /// a 500 response will be issued /// whose body is the error message in UTF-8. /// /// This can be constructed using [`new`](ErasedJson::new) /// or the [`json!`](crate::json) macro. /// /// # Example /// /// ```rust /// # use axum::{response::IntoResponse}; /// # use axum_extra::response::ErasedJson; /// async fn handler() -> ErasedJson { /// # let condition = true; /// # let foo = (); /// # let bar = vec![()]; /// // ... /// /// if condition { /// ErasedJson::new(&foo) /// } else { /// ErasedJson::new(&bar) /// } /// } /// ``` #[cfg_attr(docsrs, doc(cfg(feature = "erased-json")))] #[derive(Clone, Debug)] #[must_use] pub struct ErasedJson(Result<Bytes, Arc<serde_json::Error>>); impl ErasedJson { /// Create an `ErasedJson` by serializing a value with the compact formatter. pub fn new<T: Serialize>(val: T) -> Self { let mut bytes = BytesMut::with_capacity(128); let result = match serde_json::to_writer((&mut bytes).writer(), &val) { Ok(()) => Ok(bytes.freeze()), Err(e) => Err(Arc::new(e)), }; Self(result) } /// Create an `ErasedJson` by serializing a value with the pretty formatter. pub fn pretty<T: Serialize>(val: T) -> Self { let mut bytes = BytesMut::with_capacity(128); let result = match serde_json::to_writer_pretty((&mut bytes).writer(), &val) { Ok(()) => { bytes.put_u8(b'\n'); Ok(bytes.freeze()) } Err(e) => Err(Arc::new(e)), }; Self(result) } } impl IntoResponse for ErasedJson { fn into_response(self) -> Response { match self.0 { Ok(bytes) => ( [( header::CONTENT_TYPE, HeaderValue::from_static(mime::APPLICATION_JSON.as_ref()), )], bytes, ) .into_response(), Err(err) => (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()).into_response(), } } } /// Construct an [`ErasedJson`] response from a JSON literal. /// /// A `Content-Type: application/json` header is automatically added. /// Any variable or expression implementing [`Serialize`] /// can be interpolated as a value in the literal. /// If the [`Serialize`] implementation fails, /// or if a map with non-string keys is used, /// a 500 response will be issued /// whose body is the error message in UTF-8. /// /// Internally, /// this function uses the [`typed_json::json!`] macro, /// allowing it to perform far fewer allocations /// than a dynamic macro like [`serde_json::json!`] would – /// it's equivalent to if you had just written /// `derive(Serialize)` on a struct. /// /// # Examples /// /// ``` /// use axum::{ /// Router, /// extract::Path, /// response::Response, /// routing::get, /// }; /// use axum_extra::response::ErasedJson; /// /// async fn get_user(Path(user_id) : Path<u64>) -> ErasedJson { /// let user_name = find_user_name(user_id).await; /// axum_extra::json!({ "name": user_name }) /// } /// /// async fn find_user_name(user_id: u64) -> String { /// // ... /// # unimplemented!() /// } /// /// let app = Router::new().route("/users/{id}", get(get_user)); /// # let _: Router = app; /// ``` /// /// Trailing commas are allowed in both arrays and objects. /// /// ``` /// let response = axum_extra::json!(["trailing",]); /// ``` #[macro_export] macro_rules! json { ($($t:tt)*) => { $crate::response::ErasedJson::new( $crate::response::__private_erased_json::typed_json::json!($($t)*) ) } } /// Not public API. Re-exported as `crate::response::__private_erased_json`. #[doc(hidden)] pub mod private { pub use typed_json; }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/response/mod.rs
axum-extra/src/response/mod.rs
//! Additional types for generating responses. #[cfg(feature = "erased-json")] mod erased_json; #[cfg(feature = "attachment")] mod attachment; #[cfg(feature = "multipart")] pub mod multiple; #[cfg(feature = "error-response")] mod error_response; #[cfg(feature = "file-stream")] /// Module for handling file streams. pub mod file_stream; #[cfg(feature = "file-stream")] pub use file_stream::FileStream; #[cfg(feature = "error-response")] pub use error_response::InternalServerError; #[cfg(feature = "erased-json")] pub use erased_json::ErasedJson; /// _not_ public API #[cfg(feature = "erased-json")] #[doc(hidden)] pub use erased_json::private as __private_erased_json; #[cfg(feature = "json-lines")] #[doc(no_inline)] pub use crate::json_lines::JsonLines; #[cfg(feature = "attachment")] pub use attachment::Attachment; macro_rules! mime_response { ( $(#[$m:meta])* $ident:ident, $mime:ident, ) => { mime_response! { $(#[$m])* $ident, mime::$mime.as_ref(), } }; ( $(#[$m:meta])* $ident:ident, $mime:expr, ) => { $(#[$m])* #[derive(Clone, Copy, Debug)] #[must_use] pub struct $ident<T>(pub T); impl<T> axum_core::response::IntoResponse for $ident<T> where T: axum_core::response::IntoResponse, { fn into_response(self) -> axum_core::response::Response { ( [( http::header::CONTENT_TYPE, http::HeaderValue::from_static($mime), )], self.0, ) .into_response() } } impl<T> From<T> for $ident<T> { fn from(inner: T) -> Self { Self(inner) } } }; } mime_response! { /// A JavaScript response. /// /// Will automatically get `Content-Type: application/javascript; charset=utf-8`. JavaScript, APPLICATION_JAVASCRIPT_UTF_8, } mime_response! { /// A CSS response. /// /// Will automatically get `Content-Type: text/css; charset=utf-8`. Css, TEXT_CSS_UTF_8, } mime_response! { /// A WASM response. /// /// Will automatically get `Content-Type: application/wasm`. Wasm, "application/wasm", } #[cfg(feature = "typed-header")] #[doc(no_inline)] pub use crate::typed_header::TypedHeader;
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-extra/src/response/file_stream.rs
axum-extra/src/response/file_stream.rs
use axum_core::{ body, response::{IntoResponse, Response}, BoxError, }; use bytes::Bytes; use futures_core::TryStream; use http::{header, StatusCode}; use std::{io, path::Path}; use tokio::{ fs::File, io::{AsyncReadExt, AsyncSeekExt}, }; use tokio_util::io::ReaderStream; /// Encapsulate the file stream. /// /// The encapsulated file stream construct requires passing in a stream. /// /// # Examples /// /// ``` /// use axum::{ /// http::StatusCode, /// response::{IntoResponse, Response}, /// routing::get, /// Router, /// }; /// use axum_extra::response::file_stream::FileStream; /// use tokio::fs::File; /// use tokio_util::io::ReaderStream; /// /// async fn file_stream() -> Result<Response, (StatusCode, String)> { /// let file = File::open("test.txt") /// .await /// .map_err(|e| (StatusCode::NOT_FOUND, format!("File not found: {e}")))?; /// /// let stream = ReaderStream::new(file); /// let file_stream_resp = FileStream::new(stream).file_name("test.txt"); /// /// Ok(file_stream_resp.into_response()) /// } /// /// let app = Router::new().route("/file-stream", get(file_stream)); /// # let _: Router = app; /// ``` #[must_use] #[derive(Debug)] pub struct FileStream<S> { /// stream. pub stream: S, /// The file name of the file. pub file_name: Option<String>, /// The size of the file. pub content_size: Option<u64>, } impl<S> FileStream<S> where S: TryStream + Send + 'static, S::Ok: Into<Bytes>, S::Error: Into<BoxError>, { /// Create a new [`FileStream`] pub fn new(stream: S) -> Self { Self { stream, file_name: None, content_size: None, } } /// Set the file name of the [`FileStream`]. /// /// This adds the attachment `Content-Disposition` header with the given `file_name`. pub fn file_name(mut self, file_name: impl Into<String>) -> Self { self.file_name = Some(file_name.into()); self } /// Set the size of the file. pub fn content_size(mut self, len: u64) -> Self { self.content_size = Some(len); self } /// Return a range response. /// /// range: (start, end, total_size) /// /// # Examples /// /// ``` /// use axum::{ /// http::StatusCode, /// response::IntoResponse, /// routing::get, /// Router, /// }; /// use axum_extra::response::file_stream::FileStream; /// use tokio::fs::File; /// use tokio::io::AsyncSeekExt; /// use tokio_util::io::ReaderStream; /// /// async fn range_response() -> Result<impl IntoResponse, (StatusCode, String)> { /// let mut file = File::open("test.txt") /// .await /// .map_err(|e| (StatusCode::NOT_FOUND, format!("File not found: {e}")))?; /// let mut file_size = file /// .metadata() /// .await /// .map_err(|e| (StatusCode::NOT_FOUND, format!("Get file size: {e}")))? /// .len(); /// /// file.seek(std::io::SeekFrom::Start(10)) /// .await /// .map_err(|e| (StatusCode::NOT_FOUND, format!("File seek error: {e}")))?; /// let stream = ReaderStream::new(file); /// /// Ok(FileStream::new(stream).into_range_response(10, file_size - 1, file_size)) /// } /// /// let app = Router::new().route("/file-stream", get(range_response)); /// # let _: Router = app; /// ``` pub fn into_range_response(self, start: u64, end: u64, total_size: u64) -> Response { let mut resp = Response::builder().header(header::CONTENT_TYPE, "application/octet-stream"); resp = resp.status(StatusCode::PARTIAL_CONTENT); resp = resp.header( header::CONTENT_RANGE, format!("bytes {start}-{end}/{total_size}"), ); resp.body(body::Body::from_stream(self.stream)) .unwrap_or_else(|e| { ( StatusCode::INTERNAL_SERVER_ERROR, format!("build FileStream response error: {e}"), ) .into_response() }) } /// Attempts to return RANGE requests directly from the file path. /// /// # Arguments /// /// * `file_path` - The path of the file to be streamed /// * `start` - The start position of the range /// * `end` - The end position of the range /// /// # Note /// /// * If `end` is 0, then it is used as `file_size - 1` /// * If `start` > `file_size` or `start` > `end`, then `Range Not Satisfiable` is returned /// /// # Examples /// /// ``` /// use axum::{ /// http::StatusCode, /// response::IntoResponse, /// Router, /// routing::get /// }; /// use std::path::Path; /// use axum_extra::response::file_stream::FileStream; /// use tokio::fs::File; /// use tokio_util::io::ReaderStream; /// use tokio::io::AsyncSeekExt; /// /// async fn range_stream() -> impl IntoResponse { /// let range_start = 0; /// let range_end = 1024; /// /// FileStream::<ReaderStream<File>>::try_range_response("CHANGELOG.md", range_start, range_end).await /// .map_err(|e| (StatusCode::NOT_FOUND, format!("File not found: {e}"))) /// } /// /// let app = Router::new().route("/file-stream", get(range_stream)); /// # let _: Router = app; /// ``` pub async fn try_range_response( file_path: impl AsRef<Path>, start: u64, mut end: u64, ) -> io::Result<Response> { let mut file = File::open(file_path).await?; let metadata = file.metadata().await?; let total_size = metadata.len(); if total_size == 0 { return Ok((StatusCode::RANGE_NOT_SATISFIABLE, "Range Not Satisfiable").into_response()); } if end == 0 { end = total_size - 1; } if start > total_size { return Ok((StatusCode::RANGE_NOT_SATISFIABLE, "Range Not Satisfiable").into_response()); } if start > end { return Ok((StatusCode::RANGE_NOT_SATISFIABLE, "Range Not Satisfiable").into_response()); } if end >= total_size { return Ok((StatusCode::RANGE_NOT_SATISFIABLE, "Range Not Satisfiable").into_response()); } file.seek(std::io::SeekFrom::Start(start)).await?; let stream = ReaderStream::new(file.take(end - start + 1)); Ok(FileStream::new(stream).into_range_response(start, end, total_size)) } } // Split because the general impl requires to specify `S` and this one does not. impl FileStream<ReaderStream<File>> { /// Create a [`FileStream`] from a file path. /// /// # Examples /// /// ``` /// use axum::{ /// http::StatusCode, /// response::IntoResponse, /// Router, /// routing::get /// }; /// use axum_extra::response::file_stream::FileStream; /// /// async fn file_stream() -> impl IntoResponse { /// FileStream::from_path("test.txt") /// .await /// .map_err(|e| (StatusCode::NOT_FOUND, format!("File not found: {e}"))) /// } /// /// let app = Router::new().route("/file-stream", get(file_stream)); /// # let _: Router = app; /// ``` pub async fn from_path(path: impl AsRef<Path>) -> io::Result<Self> { let file = File::open(&path).await?; let mut content_size = None; let mut file_name = None; if let Ok(metadata) = file.metadata().await { content_size = Some(metadata.len()); } if let Some(file_name_os) = path.as_ref().file_name() { if let Some(file_name_str) = file_name_os.to_str() { file_name = Some(file_name_str.to_owned()); } } Ok(Self { stream: ReaderStream::new(file), file_name, content_size, }) } } impl<S> IntoResponse for FileStream<S> where S: TryStream + Send + 'static, S::Ok: Into<Bytes>, S::Error: Into<BoxError>, { fn into_response(self) -> Response { let mut resp = Response::builder().header(header::CONTENT_TYPE, "application/octet-stream"); if let Some(file_name) = self.file_name { resp = resp.header( header::CONTENT_DISPOSITION, format!("attachment; filename=\"{file_name}\""), ); } if let Some(content_size) = self.content_size { resp = resp.header(header::CONTENT_LENGTH, content_size); } resp.body(body::Body::from_stream(self.stream)) .unwrap_or_else(|e| { ( StatusCode::INTERNAL_SERVER_ERROR, format!("build FileStream response error: {e}"), ) .into_response() }) } } #[cfg(test)] mod tests { use super::*; use axum::{extract::Request, routing::get, Router}; use body::Body; use http::HeaderMap; use http_body_util::BodyExt; use std::io::Cursor; use tokio_util::io::ReaderStream; use tower::ServiceExt; #[tokio::test] async fn response() -> Result<(), Box<dyn std::error::Error>> { let app = Router::new().route( "/file", get(|| async { // Simulating a file stream let file_content = b"Hello, this is the simulated file content!".to_vec(); let reader = Cursor::new(file_content); // Response file stream // Content size and file name are not attached by default let stream = ReaderStream::new(reader); FileStream::new(stream).into_response() }), ); // Simulating a GET request let response = app .oneshot(Request::builder().uri("/file").body(Body::empty())?) .await?; // Validate Response Status Code assert_eq!(response.status(), StatusCode::OK); // Validate Response Headers assert_eq!( response.headers().get("content-type").unwrap(), "application/octet-stream" ); // Validate Response Body let body: &[u8] = &response.into_body().collect().await?.to_bytes(); assert_eq!( std::str::from_utf8(body)?, "Hello, this is the simulated file content!" ); Ok(()) } #[tokio::test] async fn response_not_set_filename() -> Result<(), Box<dyn std::error::Error>> { let app = Router::new().route( "/file", get(|| async { // Simulating a file stream let file_content = b"Hello, this is the simulated file content!".to_vec(); let size = file_content.len() as u64; let reader = Cursor::new(file_content); // Response file stream let stream = ReaderStream::new(reader); FileStream::new(stream).content_size(size).into_response() }), ); // Simulating a GET request let response = app .oneshot(Request::builder().uri("/file").body(Body::empty())?) .await?; // Validate Response Status Code assert_eq!(response.status(), StatusCode::OK); // Validate Response Headers assert_eq!( response.headers().get("content-type").unwrap(), "application/octet-stream" ); assert_eq!(response.headers().get("content-length").unwrap(), "42"); // Validate Response Body let body: &[u8] = &response.into_body().collect().await?.to_bytes(); assert_eq!( std::str::from_utf8(body)?, "Hello, this is the simulated file content!" ); Ok(()) } #[tokio::test] async fn response_not_set_content_size() -> Result<(), Box<dyn std::error::Error>> { let app = Router::new().route( "/file", get(|| async { // Simulating a file stream let file_content = b"Hello, this is the simulated file content!".to_vec(); let reader = Cursor::new(file_content); // Response file stream let stream = ReaderStream::new(reader); FileStream::new(stream).file_name("test").into_response() }), ); // Simulating a GET request let response = app .oneshot(Request::builder().uri("/file").body(Body::empty())?) .await?; // Validate Response Status Code assert_eq!(response.status(), StatusCode::OK); // Validate Response Headers assert_eq!( response.headers().get("content-type").unwrap(), "application/octet-stream" ); assert_eq!( response.headers().get("content-disposition").unwrap(), "attachment; filename=\"test\"" ); // Validate Response Body let body: &[u8] = &response.into_body().collect().await?.to_bytes(); assert_eq!( std::str::from_utf8(body)?, "Hello, this is the simulated file content!" ); Ok(()) } #[tokio::test] async fn response_with_content_size_and_filename() -> Result<(), Box<dyn std::error::Error>> { let app = Router::new().route( "/file", get(|| async { // Simulating a file stream let file_content = b"Hello, this is the simulated file content!".to_vec(); let size = file_content.len() as u64; let reader = Cursor::new(file_content); // Response file stream let stream = ReaderStream::new(reader); FileStream::new(stream) .file_name("test") .content_size(size) .into_response() }), ); // Simulating a GET request let response = app .oneshot(Request::builder().uri("/file").body(Body::empty())?) .await?; // Validate Response Status Code assert_eq!(response.status(), StatusCode::OK); // Validate Response Headers assert_eq!( response.headers().get("content-type").unwrap(), "application/octet-stream" ); assert_eq!( response.headers().get("content-disposition").unwrap(), "attachment; filename=\"test\"" ); assert_eq!(response.headers().get("content-length").unwrap(), "42"); // Validate Response Body let body: &[u8] = &response.into_body().collect().await?.to_bytes(); assert_eq!( std::str::from_utf8(body)?, "Hello, this is the simulated file content!" ); Ok(()) } #[tokio::test] async fn response_from_path() -> Result<(), Box<dyn std::error::Error>> { let app = Router::new().route( "/from_path", get(move || async move { FileStream::from_path(Path::new("CHANGELOG.md")) .await .unwrap() .into_response() }), ); // Simulating a GET request let response = app .oneshot( Request::builder() .uri("/from_path") .body(Body::empty()) .unwrap(), ) .await .unwrap(); // Validate Response Status Code assert_eq!(response.status(), StatusCode::OK); // Validate Response Headers assert_eq!( response.headers().get("content-type").unwrap(), "application/octet-stream" ); assert_eq!( response.headers().get("content-disposition").unwrap(), "attachment; filename=\"CHANGELOG.md\"" ); let file = File::open("CHANGELOG.md").await.unwrap(); // get file size let content_length = file.metadata().await.unwrap().len(); assert_eq!( response .headers() .get("content-length") .unwrap() .to_str() .unwrap(), content_length.to_string() ); Ok(()) } #[tokio::test] async fn response_range_file() -> Result<(), Box<dyn std::error::Error>> { let app = Router::new().route("/range_response", get(range_stream)); // Simulating a GET request let response = app .oneshot( Request::builder() .uri("/range_response") .header(header::RANGE, "bytes=20-1000") .body(Body::empty()) .unwrap(), ) .await .unwrap(); // Validate Response Status Code assert_eq!(response.status(), StatusCode::PARTIAL_CONTENT); // Validate Response Headers assert_eq!( response.headers().get("content-type").unwrap(), "application/octet-stream" ); let file = File::open("CHANGELOG.md").await.unwrap(); // get file size let content_length = file.metadata().await.unwrap().len(); assert_eq!( response .headers() .get("content-range") .unwrap() .to_str() .unwrap(), format!("bytes 20-1000/{content_length}") ); Ok(()) } async fn range_stream(headers: HeaderMap) -> Response { let range_header = headers .get(header::RANGE) .and_then(|value| value.to_str().ok()); let (start, end) = if let Some(range) = range_header { if let Some(range) = parse_range_header(range) { range } else { return (StatusCode::RANGE_NOT_SATISFIABLE, "Invalid Range").into_response(); } } else { (0, 0) // default range end = 0, if end = 0 end == file size - 1 }; FileStream::<ReaderStream<File>>::try_range_response(Path::new("CHANGELOG.md"), start, end) .await .unwrap() } fn parse_range_header(range: &str) -> Option<(u64, u64)> { let range = range.strip_prefix("bytes=")?; let mut parts = range.split('-'); let start = parts.next()?.parse::<u64>().ok()?; let end = parts .next() .and_then(|s| s.parse::<u64>().ok()) .unwrap_or(0); if start > end { return None; } Some((start, end)) } #[tokio::test] async fn response_range_empty_file() -> Result<(), Box<dyn std::error::Error>> { let file = tempfile::NamedTempFile::new()?; file.as_file().set_len(0)?; let path = file.path().to_owned(); let app = Router::new().route( "/range_empty", get(move |headers: HeaderMap| { let path = path.clone(); async move { let range_header = headers .get(header::RANGE) .and_then(|value| value.to_str().ok()); let (start, end) = if let Some(range) = range_header { if let Some(range) = parse_range_header(range) { range } else { return (StatusCode::RANGE_NOT_SATISFIABLE, "Invalid Range") .into_response(); } } else { (0, 0) }; FileStream::<ReaderStream<File>>::try_range_response(path, start, end) .await .unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response()) } }), ); let response = app .oneshot( Request::builder() .uri("/range_empty") .header(header::RANGE, "bytes=0-") .body(Body::empty()) .unwrap(), ) .await .unwrap(); assert_eq!(response.status(), StatusCode::RANGE_NOT_SATISFIABLE); Ok(()) } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/tls-graceful-shutdown/src/main.rs
examples/tls-graceful-shutdown/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p example-tls-graceful-shutdown //! ``` use axum::{ handler::HandlerWithoutStateExt, http::{StatusCode, Uri}, response::Redirect, routing::get, BoxError, Router, }; use axum_server::tls_rustls::RustlsConfig; use std::{future::Future, net::SocketAddr, path::PathBuf, time::Duration}; use tokio::signal; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[derive(Clone, Copy)] struct Ports { http: u16, https: u16, } #[tokio::main] async fn main() { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env() .unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()), ) .with(tracing_subscriber::fmt::layer()) .init(); let ports = Ports { http: 7878, https: 3000, }; //Create a handle for our TLS server so the shutdown signal can all shutdown let handle = axum_server::Handle::new(); //save the future for easy shutting down of redirect server let shutdown_future = shutdown_signal(handle.clone()); // optional: spawn a second server to redirect http requests to this server tokio::spawn(redirect_http_to_https(ports, shutdown_future)); // configure certificate and private key used by https let config = RustlsConfig::from_pem_file( PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("self_signed_certs") .join("cert.pem"), PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("self_signed_certs") .join("key.pem"), ) .await .unwrap(); let app = Router::new().route("/", get(handler)); // run https server let addr = SocketAddr::from(([127, 0, 0, 1], ports.https)); tracing::debug!("listening on {addr}"); axum_server::bind_rustls(addr, config) .handle(handle) .serve(app.into_make_service()) .await .unwrap(); } async fn shutdown_signal(handle: axum_server::Handle<SocketAddr>) { let ctrl_c = async { signal::ctrl_c() .await .expect("failed to install Ctrl+C handler"); }; #[cfg(unix)] let terminate = async { signal::unix::signal(signal::unix::SignalKind::terminate()) .expect("failed to install signal handler") .recv() .await; }; #[cfg(not(unix))] let terminate = std::future::pending::<()>(); tokio::select! { _ = ctrl_c => {}, _ = terminate => {}, } tracing::info!("Received termination signal shutting down"); handle.graceful_shutdown(Some(Duration::from_secs(10))); // 10 secs is how long docker will wait // to force shutdown } async fn handler() -> &'static str { "Hello, World!" } async fn redirect_http_to_https<F>(ports: Ports, signal: F) where F: Future<Output = ()> + Send + 'static, { fn make_https(uri: Uri, https_port: u16) -> Result<Uri, BoxError> { let mut parts = uri.into_parts(); parts.scheme = Some(axum::http::uri::Scheme::HTTPS); parts.authority = Some(format!("localhost:{https_port}").parse()?); if parts.path_and_query.is_none() { parts.path_and_query = Some("/".parse().unwrap()); } Ok(Uri::from_parts(parts)?) } let redirect = move |uri: Uri| async move { match make_https(uri, ports.https) { Ok(uri) => Ok(Redirect::permanent(&uri.to_string())), Err(error) => { tracing::warn!(%error, "failed to convert URI to HTTPS"); Err(StatusCode::BAD_REQUEST) } } }; let addr = SocketAddr::from(([127, 0, 0, 1], ports.http)); let listener = tokio::net::TcpListener::bind(addr).await.unwrap(); tracing::debug!("listening on {addr}"); axum::serve(listener, redirect.into_make_service()) .with_graceful_shutdown(signal) .await; }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/customize-path-rejection/src/main.rs
examples/customize-path-rejection/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p example-customize-path-rejection //! ``` use axum::{ extract::{path::ErrorKind, rejection::PathRejection, FromRequestParts}, http::{request::Parts, StatusCode}, response::IntoResponse, routing::get, Router, }; use serde::{de::DeserializeOwned, Deserialize, Serialize}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] async fn main() { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env() .unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()), ) .with(tracing_subscriber::fmt::layer()) .init(); // build our application with a route let app = Router::new().route("/users/{user_id}/teams/{team_id}", get(handler)); // 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; } async fn handler(Path(params): Path<Params>) -> impl IntoResponse { axum::Json(params) } #[derive(Debug, Deserialize, Serialize)] struct Params { user_id: u32, team_id: u32, } // We define our own `Path` extractor that customizes the error from `axum::extract::Path` struct Path<T>(T); impl<S, T> FromRequestParts<S> for Path<T> where // these trait bounds are copied from `impl FromRequest for axum::extract::path::Path` T: DeserializeOwned + Send, S: Send + Sync, { type Rejection = (StatusCode, axum::Json<PathError>); async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { match axum::extract::Path::<T>::from_request_parts(parts, state).await { Ok(value) => Ok(Self(value.0)), Err(rejection) => { let (status, body) = match rejection { PathRejection::FailedToDeserializePathParams(inner) => { let mut status = StatusCode::BAD_REQUEST; let kind = inner.into_kind(); let body = match &kind { ErrorKind::WrongNumberOfParameters { .. } => PathError { message: kind.to_string(), location: None, }, ErrorKind::ParseErrorAtKey { key, .. } => PathError { message: kind.to_string(), location: Some(key.clone()), }, ErrorKind::ParseErrorAtIndex { index, .. } => PathError { message: kind.to_string(), location: Some(index.to_string()), }, ErrorKind::ParseError { .. } => PathError { message: kind.to_string(), location: None, }, ErrorKind::InvalidUtf8InPathParam { key } => PathError { message: kind.to_string(), location: Some(key.clone()), }, ErrorKind::UnsupportedType { .. } => { // this error is caused by the programmer using an unsupported type // (such as nested maps) so respond with `500` instead status = StatusCode::INTERNAL_SERVER_ERROR; PathError { message: kind.to_string(), location: None, } } ErrorKind::Message(msg) => PathError { message: msg.clone(), location: None, }, _ => PathError { message: format!("Unhandled deserialization error: {kind}"), location: None, }, }; (status, body) } PathRejection::MissingPathParams(error) => ( StatusCode::INTERNAL_SERVER_ERROR, PathError { message: error.to_string(), location: None, }, ), _ => ( StatusCode::INTERNAL_SERVER_ERROR, PathError { message: format!("Unhandled path rejection: {rejection}"), location: None, }, ), }; Err((status, axum::Json(body))) } } } } #[derive(Serialize)] struct PathError { message: String, location: Option<String>, }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/chat/src/main.rs
examples/chat/src/main.rs
//! Example chat application. //! //! Run with //! //! ```not_rust //! cargo run -p example-chat //! ``` use axum::{ extract::{ ws::{Message, Utf8Bytes, WebSocket, WebSocketUpgrade}, State, }, response::{Html, IntoResponse}, routing::get, Router, }; use futures_util::{sink::SinkExt, stream::StreamExt}; use std::{ collections::HashSet, sync::{Arc, Mutex}, }; use tokio::sync::broadcast; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; // Our shared state struct AppState { // We require unique usernames. This tracks which usernames have been taken. user_set: Mutex<HashSet<String>>, // Channel used to send messages to all connected clients. tx: broadcast::Sender<String>, } #[tokio::main] async fn main() { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env() .unwrap_or_else(|_| format!("{}=trace", env!("CARGO_CRATE_NAME")).into()), ) .with(tracing_subscriber::fmt::layer()) .init(); // Set up application state for use with with_state(). let user_set = Mutex::new(HashSet::new()); let (tx, _rx) = broadcast::channel(100); let app_state = Arc::new(AppState { user_set, tx }); let app = Router::new() .route("/", get(index)) .route("/websocket", get(websocket_handler)) .with_state(app_state); 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; } async fn websocket_handler( ws: WebSocketUpgrade, State(state): State<Arc<AppState>>, ) -> impl IntoResponse { ws.on_upgrade(|socket| websocket(socket, state)) } // This function deals with a single websocket connection, i.e., a single // connected client / user, for which we will spawn two independent tasks (for // receiving / sending chat messages). async fn websocket(stream: WebSocket, state: Arc<AppState>) { // By splitting, we can send and receive at the same time. let (mut sender, mut receiver) = stream.split(); // Username gets set in the receive loop, if it's valid. let mut username = String::new(); // Loop until a text message is found. while let Some(Ok(message)) = receiver.next().await { if let Message::Text(name) = message { // If username that is sent by client is not taken, fill username string. check_username(&state, &mut username, name.as_str()); // If not empty we want to quit the loop else we want to quit function. if !username.is_empty() { break; } else { // Only send our client that username is taken. let _ = sender .send(Message::Text(Utf8Bytes::from_static( "Username already taken.", ))) .await; return; } } } // We subscribe *before* sending the "joined" message, so that we will also // display it to our client. let mut rx = state.tx.subscribe(); // Now send the "joined" message to all subscribers. let msg = format!("{username} joined."); tracing::debug!("{msg}"); let _ = state.tx.send(msg); // Spawn the first task that will receive broadcast messages and send text // messages over the websocket to our client. let mut send_task = tokio::spawn(async move { while let Ok(msg) = rx.recv().await { // In any websocket error, break loop. if sender.send(Message::text(msg)).await.is_err() { break; } } }); // Clone things we want to pass (move) to the receiving task. let tx = state.tx.clone(); let name = username.clone(); // Spawn a task that takes messages from the websocket, prepends the user // name, and sends them to all broadcast subscribers. let mut recv_task = tokio::spawn(async move { while let Some(Ok(Message::Text(text))) = receiver.next().await { // Add username before message. let _ = tx.send(format!("{name}: {text}")); } }); // If any one of the tasks run to completion, we abort the other. tokio::select! { _ = &mut send_task => recv_task.abort(), _ = &mut recv_task => send_task.abort(), }; // Send "user left" message (similar to "joined" above). let msg = format!("{username} left."); tracing::debug!("{msg}"); let _ = state.tx.send(msg); // Remove username from map so new clients can take it again. state.user_set.lock().unwrap().remove(&username); } fn check_username(state: &AppState, string: &mut String, name: &str) { let mut user_set = state.user_set.lock().unwrap(); if !user_set.contains(name) { user_set.insert(name.to_owned()); string.push_str(name); } } // Include utf-8 file at **compile** time. async fn index() -> Html<&'static str> { Html(std::include_str!("../chat.html")) }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/consume-body-in-extractor-or-middleware/src/main.rs
examples/consume-body-in-extractor-or-middleware/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p example-consume-body-in-extractor-or-middleware //! ``` use axum::{ body::{Body, Bytes}, extract::{FromRequest, Request}, http::StatusCode, middleware::{self, Next}, response::{IntoResponse, Response}, routing::post, Router, }; use http_body_util::BodyExt; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] async fn main() { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env() .unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()), ) .with(tracing_subscriber::fmt::layer()) .init(); let app = Router::new() .route("/", post(handler)) .layer(middleware::from_fn(print_request_body)); 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; } // middleware that shows how to consume the request body upfront async fn print_request_body(request: Request, next: Next) -> Result<impl IntoResponse, Response> { let request = buffer_request_body(request).await?; Ok(next.run(request).await) } // 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<Request, Response> { let (parts, body) = request.into_parts(); // this won't work if the body is an long running stream let bytes = body .collect() .await .map_err(|err| (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()).into_response())? .to_bytes(); do_thing_with_request_body(bytes.clone()); Ok(Request::from_parts(parts, Body::from(bytes))) } fn do_thing_with_request_body(bytes: Bytes) { tracing::debug!(body = ?bytes); } async fn handler(BufferRequestBody(body): BufferRequestBody) { tracing::debug!(?body, "handler received body"); } // extractor that shows how to consume the request body upfront struct BufferRequestBody(Bytes); // we must implement `FromRequest` (and not `FromRequestParts`) to consume the body impl<S> FromRequest<S> for BufferRequestBody where S: Send + Sync, { type Rejection = Response; async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> { let body = Bytes::from_request(req, state) .await .map_err(|err| err.into_response())?; do_thing_with_request_body(body.clone()); Ok(Self(body)) } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/request-id/src/main.rs
examples/request-id/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p example-request-id //! ``` use axum::{ http::{HeaderName, Request}, response::Html, routing::get, Router, }; use tower::ServiceBuilder; use tower_http::{ request_id::{MakeRequestUuid, PropagateRequestIdLayer, SetRequestIdLayer}, trace::TraceLayer, }; use tracing::{error, info, info_span}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; const REQUEST_ID_HEADER: &str = "x-request-id"; #[tokio::main] async fn main() { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| { // axum logs rejections from built-in extractors with the `axum::rejection` // target, at `TRACE` level. `axum::rejection=trace` enables showing those events format!( "{}=debug,tower_http=debug,axum::rejection=trace", env!("CARGO_CRATE_NAME") ) .into() }), ) .with(tracing_subscriber::fmt::layer()) .init(); let x_request_id = HeaderName::from_static(REQUEST_ID_HEADER); let middleware = ServiceBuilder::new() .layer(SetRequestIdLayer::new( x_request_id.clone(), MakeRequestUuid, )) .layer( TraceLayer::new_for_http().make_span_with(|request: &Request<_>| { // Log the request id as generated. let request_id = request.headers().get(REQUEST_ID_HEADER); match request_id { Some(request_id) => info_span!( "http_request", request_id = ?request_id, ), None => { error!("could not extract request_id"); info_span!("http_request") } } }), ) // send headers from request to response headers .layer(PropagateRequestIdLayer::new(x_request_id)); // build our application with a route let app = Router::new().route("/", get(handler)).layer(middleware); // run it 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; } async fn handler() -> Html<&'static str> { info!("Hello world!"); Html("<h1>Hello, World!</h1>") }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/serve-with-hyper/src/main.rs
examples/serve-with-hyper/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p example-serve-with-hyper //! ``` //! //! This example shows how to run axum using hyper's low level API. //! //! The [hyper-util] crate exists to provide high level utilities but it's still in early stages of //! development. //! //! [hyper-util]: https://crates.io/crates/hyper-util use std::convert::Infallible; use std::net::SocketAddr; use axum::extract::ConnectInfo; use axum::{extract::Request, routing::get, Router}; use hyper::body::Incoming; use hyper_util::rt::{TokioExecutor, TokioIo}; use hyper_util::server; use tokio::net::TcpListener; use tower::{Service, ServiceExt}; #[tokio::main] async fn main() { tokio::join!(serve_plain(), serve_with_connect_info()); } async fn serve_plain() { // Create a regular axum app. let app = Router::new().route("/", get(|| async { "Hello!" })); // Create a `TcpListener` using tokio. let listener = TcpListener::bind("0.0.0.0:3000").await.unwrap(); // Continuously accept new connections. loop { // In this example we discard the remote address. See `fn serve_with_connect_info` for how // to expose that. let (socket, _remote_addr) = listener.accept().await.unwrap(); // We don't need to call `poll_ready` because `Router` is always ready. let tower_service = app.clone(); // Spawn a task to handle the connection. That way we can handle multiple connections // concurrently. tokio::spawn(async move { // Hyper has its own `AsyncRead` and `AsyncWrite` traits and doesn't use tokio. // `TokioIo` converts between them. let socket = TokioIo::new(socket); // Hyper also has its own `Service` trait and doesn't use tower. We can use // `hyper::service::service_fn` to create a hyper `Service` that calls our app through // `tower::Service::call`. let hyper_service = hyper::service::service_fn(move |request: Request<Incoming>| { // We have to clone `tower_service` because hyper's `Service` uses `&self` whereas // tower's `Service` requires `&mut self`. // // We don't need to call `poll_ready` since `Router` is always ready. tower_service.clone().call(request) }); // `server::conn::auto::Builder` supports both http1 and http2. // // `TokioExecutor` tells hyper to use `tokio::spawn` to spawn tasks. if let Err(err) = server::conn::auto::Builder::new(TokioExecutor::new()) // `serve_connection_with_upgrades` is required for websockets. If you don't need // that you can use `serve_connection` instead. .serve_connection_with_upgrades(socket, hyper_service) .await { eprintln!("failed to serve connection: {err:#}"); } }); } } // Similar setup to `serve_plain` but captures the remote address and exposes it through the // `ConnectInfo` extractor async fn serve_with_connect_info() { let app = Router::new().route( "/", get( |ConnectInfo(remote_addr): ConnectInfo<SocketAddr>| async move { format!("Hello {remote_addr}") }, ), ); let mut make_service = app.into_make_service_with_connect_info::<SocketAddr>(); let listener = TcpListener::bind("0.0.0.0:3001").await.unwrap(); loop { let (socket, remote_addr) = listener.accept().await.unwrap(); // We don't need to call `poll_ready` because `IntoMakeServiceWithConnectInfo` is always // ready. let tower_service = unwrap_infallible(make_service.call(remote_addr).await); tokio::spawn(async move { let socket = TokioIo::new(socket); let hyper_service = hyper::service::service_fn(move |request: Request<Incoming>| { tower_service.clone().oneshot(request) }); if let Err(err) = server::conn::auto::Builder::new(TokioExecutor::new()) .serve_connection_with_upgrades(socket, hyper_service) .await { eprintln!("failed to serve connection: {err:#}"); } }); } } fn unwrap_infallible<T>(result: Result<T, Infallible>) -> T { match result { Ok(value) => value, Err(err) => match err {}, } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/sqlx-postgres/src/main.rs
examples/sqlx-postgres/src/main.rs
//! Example of application using <https://github.com/launchbadge/sqlx> //! //! Run with //! //! ```not_rust //! cargo run -p example-sqlx-postgres //! ``` //! //! Test with curl: //! //! ```not_rust //! curl 127.0.0.1:3000 //! curl -X POST 127.0.0.1:3000 //! ``` use axum::{ extract::{FromRef, FromRequestParts, State}, http::{request::Parts, StatusCode}, routing::get, Router, }; use sqlx::postgres::{PgPool, PgPoolOptions}; use tokio::net::TcpListener; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; use std::time::Duration; #[tokio::main] async fn main() { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env() .unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()), ) .with(tracing_subscriber::fmt::layer()) .init(); let db_connection_str = std::env::var("DATABASE_URL") .unwrap_or_else(|_| "postgres://postgres:password@localhost".to_string()); // set up connection pool let pool = PgPoolOptions::new() .max_connections(5) .acquire_timeout(Duration::from_secs(3)) .connect(&db_connection_str) .await .expect("can't connect to database"); // build our application with some routes let app = Router::new() .route( "/", get(using_connection_pool_extractor).post(using_connection_extractor), ) .with_state(pool); // run it with hyper let listener = TcpListener::bind("127.0.0.1:3000").await.unwrap(); tracing::debug!("listening on {}", listener.local_addr().unwrap()); axum::serve(listener, app).await; } // we can extract the connection pool with `State` async fn using_connection_pool_extractor( State(pool): State<PgPool>, ) -> Result<String, (StatusCode, String)> { sqlx::query_scalar("select 'hello world from pg'") .fetch_one(&pool) .await .map_err(internal_error) } // we can also write a custom extractor that grabs a connection from the pool // which setup is appropriate depends on your application struct DatabaseConnection(sqlx::pool::PoolConnection<sqlx::Postgres>); impl<S> FromRequestParts<S> for DatabaseConnection where PgPool: FromRef<S>, S: Send + Sync, { type Rejection = (StatusCode, String); async fn from_request_parts(_parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { let pool = PgPool::from_ref(state); let conn = pool.acquire().await.map_err(internal_error)?; Ok(Self(conn)) } } async fn using_connection_extractor( DatabaseConnection(mut conn): DatabaseConnection, ) -> Result<String, (StatusCode, String)> { sqlx::query_scalar("select 'hello world from pg'") .fetch_one(&mut *conn) .await .map_err(internal_error) } /// Utility function for mapping any error into a `500 Internal Server Error` /// response. fn internal_error<E>(err: E) -> (StatusCode, String) where E: std::error::Error, { (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()) }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/tracing-aka-logging/src/main.rs
examples/tracing-aka-logging/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p example-tracing-aka-logging //! ``` use axum::{ body::Bytes, extract::MatchedPath, http::{HeaderMap, Request}, response::{Html, Response}, routing::get, Router, }; 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}; #[tokio::main] async fn main() { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| { // axum logs rejections from built-in extractors with the `axum::rejection` // target, at `TRACE` level. `axum::rejection=trace` enables showing those events format!( "{}=debug,tower_http=debug,axum::rejection=trace", env!("CARGO_CRATE_NAME") ) .into() }), ) .with(tracing_subscriber::fmt::layer()) .init(); // build our application with a route let app = Router::new() .route("/", get(handler)) // `TraceLayer` is provided by tower-http so you have to add that as a dependency. // It provides good defaults but is also very customizable. // // See https://docs.rs/tower-http/0.1.1/tower_http/trace/index.html for more details. // // If you want to customize the behavior using closures here is how. .layer( TraceLayer::new_for_http() .make_span_with(|request: &Request<_>| { // Log the matched route's path (with placeholders not filled in). // Use request.uri() or OriginalUri if you want the real path. let matched_path = request .extensions() .get::<MatchedPath>() .map(MatchedPath::as_str); info_span!( "http_request", method = ?request.method(), matched_path, some_other_field = tracing::field::Empty, ) }) .on_request(|_request: &Request<_>, _span: &Span| { // You can use `_span.record("some_other_field", value)` in one of these // closures to attach a value to the initially empty field in the info_span // created above. }) .on_response(|_response: &Response, _latency: Duration, _span: &Span| { // ... }) .on_body_chunk(|_chunk: &Bytes, _latency: Duration, _span: &Span| { // ... }) .on_eos( |_trailers: Option<&HeaderMap>, _stream_duration: Duration, _span: &Span| { // ... }, ) .on_failure( |_error: ServerErrorsFailureClass, _latency: Duration, _span: &Span| { // ... }, ), ); // run it let listener = TcpListener::bind("127.0.0.1:3000").await.unwrap(); tracing::debug!("listening on {}", listener.local_addr().unwrap()); axum::serve(listener, app).await; } async fn handler() -> Html<&'static str> { Html("<h1>Hello, World!</h1>") }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/key-value-store/src/main.rs
examples/key-value-store/src/main.rs
//! Simple in-memory key/value store showing features of axum. //! //! Run with: //! //! ```not_rust //! cargo run -p example-key-value-store //! ``` use axum::{ body::Bytes, error_handling::HandleErrorLayer, extract::{DefaultBodyLimit, Path, State}, handler::Handler, http::StatusCode, response::IntoResponse, routing::{delete, get}, Router, }; use std::{ borrow::Cow, collections::HashMap, sync::{Arc, RwLock}, time::Duration, }; use tower::{BoxError, ServiceBuilder}; use tower_http::{ compression::CompressionLayer, limit::RequestBodyLimitLayer, trace::TraceLayer, validate_request::ValidateRequestHeaderLayer, }; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] async fn main() { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| { format!("{}=debug,tower_http=debug", env!("CARGO_CRATE_NAME")).into() }), ) .with(tracing_subscriber::fmt::layer()) .init(); let shared_state = SharedState::default(); // Build our application by composing routes let app = Router::new() .route( "/{key}", // Add compression to `kv_get` get(kv_get.layer(CompressionLayer::new())) // But don't compress `kv_set` .post_service( kv_set .layer(( DefaultBodyLimit::disable(), RequestBodyLimitLayer::new(1024 * 5_000 /* ~5mb */), )) .with_state(Arc::clone(&shared_state)), ), ) .route("/keys", get(list_keys)) // Nest our admin routes under `/admin` .nest("/admin", admin_routes()) // Add middleware to all routes .layer( ServiceBuilder::new() // Handle errors from middleware .layer(HandleErrorLayer::new(handle_error)) .load_shed() .concurrency_limit(1024) .timeout(Duration::from_secs(10)) .layer(TraceLayer::new_for_http()), ) .with_state(Arc::clone(&shared_state)); // Run our app with hyper 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; } type SharedState = Arc<RwLock<AppState>>; #[derive(Default)] struct AppState { db: HashMap<String, Bytes>, } async fn kv_get( Path(key): Path<String>, State(state): State<SharedState>, ) -> Result<Bytes, StatusCode> { let db = &state.read().unwrap().db; if let Some(value) = db.get(&key) { Ok(value.clone()) } else { Err(StatusCode::NOT_FOUND) } } async fn kv_set(Path(key): Path<String>, State(state): State<SharedState>, bytes: Bytes) { state.write().unwrap().db.insert(key, bytes); } async fn list_keys(State(state): State<SharedState>) -> String { let db = &state.read().unwrap().db; db.keys() .map(|key| key.to_string()) .collect::<Vec<String>>() .join("\n") } fn admin_routes() -> Router<SharedState> { async fn delete_all_keys(State(state): State<SharedState>) { state.write().unwrap().db.clear(); } async fn remove_key(Path(key): Path<String>, State(state): State<SharedState>) { state.write().unwrap().db.remove(&key); } Router::new() .route("/keys", delete(delete_all_keys)) .route("/key/{key}", delete(remove_key)) // Require bearer auth for all admin routes .layer(ValidateRequestHeaderLayer::bearer("secret-token")) } async fn handle_error(error: BoxError) -> impl IntoResponse { if error.is::<tower::timeout::error::Elapsed>() { return (StatusCode::REQUEST_TIMEOUT, Cow::from("request timed out")); } if error.is::<tower::load_shed::error::Overloaded>() { return ( StatusCode::SERVICE_UNAVAILABLE, Cow::from("service is overloaded, try again later"), ); } ( StatusCode::INTERNAL_SERVER_ERROR, Cow::from(format!("Unhandled internal error: {error}")), ) }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/mongodb/src/main.rs
examples/mongodb/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p example-mongodb //! ``` use axum::{ extract::{Path, State}, http::StatusCode, routing::{delete, get, post, put}, Json, Router, }; use mongodb::{ bson::doc, results::{DeleteResult, InsertOneResult, UpdateResult}, Client, Collection, }; use serde::{Deserialize, Serialize}; use tower_http::trace::TraceLayer; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] async fn main() { // connecting to mongodb let db_connection_str = std::env::var("DATABASE_URL").unwrap_or_else(|_| { "mongodb://admin:password@127.0.0.1:27017/?authSource=admin".to_string() }); let client = Client::with_uri_str(db_connection_str).await.unwrap(); // pinging the database client .database("axum-mongo") .run_command(doc! { "ping": 1 }) .await .unwrap(); println!("Pinged your database. Successfully connected to MongoDB!"); // logging middleware tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| { format!("{}=debug,tower_http=debug", env!("CARGO_CRATE_NAME")).into() }), ) .with(tracing_subscriber::fmt::layer()) .init(); // 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(client)).await; } // defining routes and state fn app(client: Client) -> Router { let collection: Collection<Member> = client.database("axum-mongo").collection("members"); Router::new() .route("/create", post(create_member)) .route("/read/{id}", get(read_member)) .route("/update", put(update_member)) .route("/delete/{id}", delete(delete_member)) .layer(TraceLayer::new_for_http()) .with_state(collection) } // handler to create a new member async fn create_member( State(db): State<Collection<Member>>, Json(input): Json<Member>, ) -> Result<Json<InsertOneResult>, (StatusCode, String)> { let result = db.insert_one(input).await.map_err(internal_error)?; Ok(Json(result)) } // handler to read an existing member async fn read_member( State(db): State<Collection<Member>>, Path(id): Path<u32>, ) -> Result<Json<Option<Member>>, (StatusCode, String)> { let result = db .find_one(doc! { "_id": id }) .await .map_err(internal_error)?; Ok(Json(result)) } // handler to update an existing member async fn update_member( State(db): State<Collection<Member>>, Json(input): Json<Member>, ) -> Result<Json<UpdateResult>, (StatusCode, String)> { let result = db .replace_one(doc! { "_id": input.id }, input) .await .map_err(internal_error)?; Ok(Json(result)) } // handler to delete an existing member async fn delete_member( State(db): State<Collection<Member>>, Path(id): Path<u32>, ) -> Result<Json<DeleteResult>, (StatusCode, String)> { let result = db .delete_one(doc! { "_id": id }) .await .map_err(internal_error)?; Ok(Json(result)) } fn internal_error<E>(err: E) -> (StatusCode, String) where E: std::error::Error, { (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()) } // defining Member type #[derive(Debug, Deserialize, Serialize)] struct Member { #[serde(rename = "_id")] id: u32, name: String, active: bool, }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/low-level-native-tls/src/main.rs
examples/low-level-native-tls/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p example-low-level-native-tls //! ``` use axum::{extract::Request, routing::get, Router}; use hyper::body::Incoming; use hyper_util::rt::{TokioExecutor, TokioIo}; use std::path::PathBuf; use tokio::net::TcpListener; use tokio_native_tls::{ native_tls::{Identity, Protocol, TlsAcceptor as NativeTlsAcceptor}, TlsAcceptor, }; use tower_service::Service; use tracing::{error, info, warn}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] async fn main() { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env() .unwrap_or_else(|_| "example_low_level_rustls=debug".into()), ) .with(tracing_subscriber::fmt::layer()) .init(); let tls_acceptor = native_tls_acceptor( PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("self_signed_certs") .join("key.pem"), PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("self_signed_certs") .join("cert.pem"), ); let tls_acceptor = TlsAcceptor::from(tls_acceptor); let bind = "[::1]:3000"; let tcp_listener = TcpListener::bind(bind).await.unwrap(); info!("HTTPS server listening on {bind}. To contact curl -k https://localhost:3000"); let app = Router::new().route("/", get(handler)); loop { let tower_service = app.clone(); let tls_acceptor = tls_acceptor.clone(); // Wait for new tcp connection let (cnx, addr) = tcp_listener.accept().await.unwrap(); tokio::spawn(async move { // Wait for tls handshake to happen let Ok(stream) = tls_acceptor.accept(cnx).await else { error!("error during tls handshake connection from {}", addr); return; }; // Hyper has its own `AsyncRead` and `AsyncWrite` traits and doesn't use tokio. // `TokioIo` converts between them. let stream = TokioIo::new(stream); // Hyper also has its own `Service` trait and doesn't use tower. We can use // `hyper::service::service_fn` to create a hyper `Service` that calls our app through // `tower::Service::call`. let hyper_service = hyper::service::service_fn(move |request: Request<Incoming>| { // We have to clone `tower_service` because hyper's `Service` uses `&self` whereas // tower's `Service` requires `&mut self`. // // We don't need to call `poll_ready` since `Router` is always ready. tower_service.clone().call(request) }); let ret = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new()) .serve_connection_with_upgrades(stream, hyper_service) .await; if let Err(err) = ret { warn!("error serving connection from {addr}: {err}"); } }); } } async fn handler() -> &'static str { "Hello, World!" } fn native_tls_acceptor(key_file: PathBuf, cert_file: PathBuf) -> NativeTlsAcceptor { let key_pem = std::fs::read_to_string(&key_file).unwrap(); let cert_pem = std::fs::read_to_string(&cert_file).unwrap(); let id = Identity::from_pkcs8(cert_pem.as_bytes(), key_pem.as_bytes()).unwrap(); NativeTlsAcceptor::builder(id) // let's be modern .min_protocol_version(Some(Protocol::Tlsv12)) .build() .unwrap() }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/low-level-rustls/src/main.rs
examples/low-level-rustls/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p example-low-level-rustls //! ``` use axum::{extract::Request, routing::get, Router}; use hyper::body::Incoming; use hyper_util::rt::{TokioExecutor, TokioIo}; use std::{ path::{Path, PathBuf}, sync::Arc, }; use tokio::net::TcpListener; use tokio_rustls::{ rustls::pki_types::{pem::PemObject, CertificateDer, PrivateKeyDer}, rustls::ServerConfig, TlsAcceptor, }; use tower_service::Service; use tracing::{error, info, warn}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] async fn main() { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env() .unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()), ) .with(tracing_subscriber::fmt::layer()) .init(); let rustls_config = rustls_server_config( PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("self_signed_certs") .join("key.pem"), PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("self_signed_certs") .join("cert.pem"), ); let tls_acceptor = TlsAcceptor::from(rustls_config); let bind = "[::1]:3000"; let tcp_listener = TcpListener::bind(bind).await.unwrap(); info!("HTTPS server listening on {bind}. To contact curl -k https://localhost:3000"); let app = Router::new().route("/", get(handler)); loop { let tower_service = app.clone(); let tls_acceptor = tls_acceptor.clone(); // Wait for new tcp connection let (cnx, addr) = tcp_listener.accept().await.unwrap(); tokio::spawn(async move { // Wait for tls handshake to happen let Ok(stream) = tls_acceptor.accept(cnx).await else { error!("error during tls handshake connection from {}", addr); return; }; // Hyper has its own `AsyncRead` and `AsyncWrite` traits and doesn't use tokio. // `TokioIo` converts between them. let stream = TokioIo::new(stream); // Hyper also has its own `Service` trait and doesn't use tower. We can use // `hyper::service::service_fn` to create a hyper `Service` that calls our app through // `tower::Service::call`. let hyper_service = hyper::service::service_fn(move |request: Request<Incoming>| { // We have to clone `tower_service` because hyper's `Service` uses `&self` whereas // tower's `Service` requires `&mut self`. // // We don't need to call `poll_ready` since `Router` is always ready. tower_service.clone().call(request) }); let ret = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new()) .serve_connection_with_upgrades(stream, hyper_service) .await; if let Err(err) = ret { warn!("error serving connection from {}: {}", addr, err); } }); } } async fn handler() -> &'static str { "Hello, World!" } fn rustls_server_config(key: impl AsRef<Path>, cert: impl AsRef<Path>) -> Arc<ServerConfig> { let key = PrivateKeyDer::from_pem_file(key).unwrap(); let certs = CertificateDer::pem_file_iter(cert) .unwrap() .map(|cert| cert.unwrap()) .collect(); let mut config = ServerConfig::builder() .with_no_client_auth() .with_single_cert(certs, key) .expect("bad certificate/key"); config.alpn_protocols = vec![b"h2".to_vec(), b"http/1.1".to_vec()]; Arc::new(config) }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/tokio-redis/src/main.rs
examples/tokio-redis/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p example-tokio-redis //! ``` use axum::{ extract::{FromRef, FromRequestParts, State}, http::{request::Parts, StatusCode}, routing::get, Router, }; use redis::AsyncCommands; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] async fn main() { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env() .unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()), ) .with(tracing_subscriber::fmt::layer()) .init(); tracing::debug!("connecting to redis"); let client = redis::Client::open("redis://localhost").unwrap(); let pool = bb8::Pool::builder().build(client).await.unwrap(); { // ping the database before starting let mut conn = pool.get().await.unwrap(); conn.set::<&str, &str, ()>("foo", "bar").await.unwrap(); let result: String = conn.get("foo").await.unwrap(); assert_eq!(result, "bar"); } tracing::debug!("successfully connected to redis and pinged it"); // build our application with some routes let app = Router::new() .route( "/", get(using_connection_pool_extractor).post(using_connection_extractor), ) .with_state(pool); // 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; } type ConnectionPool = bb8::Pool<redis::Client>; async fn using_connection_pool_extractor( State(pool): State<ConnectionPool>, ) -> Result<String, (StatusCode, String)> { let mut conn = pool.get().await.map_err(internal_error)?; let result: String = conn.get("foo").await.map_err(internal_error)?; Ok(result) } // we can also write a custom extractor that grabs a connection from the pool // which setup is appropriate depends on your application struct DatabaseConnection(bb8::PooledConnection<'static, redis::Client>); impl<S> FromRequestParts<S> for DatabaseConnection where ConnectionPool: FromRef<S>, S: Send + Sync, { type Rejection = (StatusCode, String); async fn from_request_parts(_parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> { let pool = ConnectionPool::from_ref(state); let conn = pool.get_owned().await.map_err(internal_error)?; Ok(Self(conn)) } } async fn using_connection_extractor( DatabaseConnection(mut conn): DatabaseConnection, ) -> Result<String, (StatusCode, String)> { let result: String = conn.get("foo").await.map_err(internal_error)?; Ok(result) } /// Utility function for mapping any error into a `500 Internal Server Error` /// response. fn internal_error<E>(err: E) -> (StatusCode, String) where E: std::error::Error, { (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()) }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/low-level-openssl/src/main.rs
examples/low-level-openssl/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p example-low-level-openssl //! ``` use axum::{http::Request, routing::get, Router}; use hyper::body::Incoming; use hyper_util::rt::{TokioExecutor, TokioIo}; use openssl::ssl::{Ssl, SslAcceptor, SslFiletype, SslMethod}; use std::{path::PathBuf, pin::Pin}; use tokio::net::TcpListener; use tokio_openssl::SslStream; use tower::Service; use tracing::{error, info, warn}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] async fn main() { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env() .unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()), ) .with(tracing_subscriber::fmt::layer()) .init(); let mut tls_builder = SslAcceptor::mozilla_modern_v5(SslMethod::tls()).unwrap(); tls_builder .set_certificate_file( PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("self_signed_certs") .join("cert.pem"), SslFiletype::PEM, ) .unwrap(); tls_builder .set_private_key_file( PathBuf::from(env!("CARGO_MANIFEST_DIR")) .join("self_signed_certs") .join("key.pem"), SslFiletype::PEM, ) .unwrap(); tls_builder.check_private_key().unwrap(); let tls_acceptor = tls_builder.build(); let bind = "[::1]:3000"; let tcp_listener = TcpListener::bind(bind).await.unwrap(); info!("HTTPS server listening on {bind}. To contact curl -k https://localhost:3000"); let app = Router::new().route("/", get(handler)); loop { let tower_service = app.clone(); let tls_acceptor = tls_acceptor.clone(); // Wait for new tcp connection let (cnx, addr) = tcp_listener.accept().await.unwrap(); tokio::spawn(async move { let ssl = Ssl::new(tls_acceptor.context()).unwrap(); let mut tls_stream = SslStream::new(ssl, cnx).unwrap(); if let Err(err) = SslStream::accept(Pin::new(&mut tls_stream)).await { error!( "error during tls handshake connection from {}: {}", addr, err ); return; } // Hyper has its own `AsyncRead` and `AsyncWrite` traits and doesn't use tokio. // `TokioIo` converts between them. let stream = TokioIo::new(tls_stream); // Hyper also has its own `Service` trait and doesn't use tower. We can use // `hyper::service::service_fn` to create a hyper `Service` that calls our app through // `tower::Service::call`. let hyper_service = hyper::service::service_fn(move |request: Request<Incoming>| { // We have to clone `tower_service` because hyper's `Service` uses `&self` whereas // tower's `Service` requires `&mut self`. // // We don't need to call `poll_ready` since `Router` is always ready. tower_service.clone().call(request) }); let ret = hyper_util::server::conn::auto::Builder::new(TokioExecutor::new()) .serve_connection_with_upgrades(stream, hyper_service) .await; if let Err(err) = ret { warn!("error serving connection from {}: {}", addr, err); } }); } } async fn handler() -> &'static str { "Hello, World!" }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/versioning/src/main.rs
examples/versioning/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p example-versioning //! ``` use axum::{ extract::{FromRequestParts, Path}, http::{request::Parts, StatusCode}, response::{Html, IntoResponse, Response}, routing::get, RequestPartsExt, Router, }; use std::collections::HashMap; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] async fn main() { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env() .unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()), ) .with(tracing_subscriber::fmt::layer()) .init(); // build our application with some routes let app = app(); // 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; } fn app() -> Router { Router::new().route("/{version}/foo", get(handler)) } async fn handler(version: Version) -> Html<String> { Html(format!("received request with version {version:?}")) } #[derive(Debug)] enum Version { V1, V2, V3, } impl<S> FromRequestParts<S> for Version where S: Send + Sync, { type Rejection = Response; async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> { let params: Path<HashMap<String, String>> = parts.extract().await.map_err(IntoResponse::into_response)?; let version = params .get("version") .ok_or_else(|| (StatusCode::NOT_FOUND, "version param missing").into_response())?; match version.as_str() { "v1" => Ok(Version::V1), "v2" => Ok(Version::V2), "v3" => Ok(Version::V3), _ => Err((StatusCode::NOT_FOUND, "unknown version").into_response()), } } } #[cfg(test)] mod tests { use super::*; use axum::{body::Body, http::Request, http::StatusCode}; use http_body_util::BodyExt; use tower::ServiceExt; #[tokio::test] async fn test_v1() { let response = app() .oneshot( Request::builder() .uri("/v1/foo") .body(Body::empty()) .unwrap(), ) .await .unwrap(); assert_eq!(response.status(), StatusCode::OK); let body = response.into_body(); let bytes = body.collect().await.unwrap().to_bytes(); let html = String::from_utf8(bytes.to_vec()).unwrap(); assert_eq!(html, "received request with version V1"); } #[tokio::test] async fn test_v4() { let response = app() .oneshot( Request::builder() .uri("/v4/foo") .body(Body::empty()) .unwrap(), ) .await .unwrap(); assert_eq!(response.status(), StatusCode::NOT_FOUND); let body = response.into_body(); let bytes = body.collect().await.unwrap().to_bytes(); let html = String::from_utf8(bytes.to_vec()).unwrap(); assert_eq!(html, "unknown version"); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/http-proxy/src/main.rs
examples/http-proxy/src/main.rs
//! Run with //! //! ```not_rust //! $ cargo run -p example-http-proxy //! ``` //! //! In another terminal: //! //! ```not_rust //! $ curl -v -x "127.0.0.1:3000" https://tokio.rs //! ``` //! //! Example is based on <https://github.com/hyperium/hyper/blob/master/examples/http_proxy.rs> use axum::{ body::Body, extract::Request, http::{Method, StatusCode}, response::{IntoResponse, Response}, routing::get, Router, }; use hyper::body::Incoming; use hyper::server::conn::http1; use hyper::upgrade::Upgraded; use std::net::SocketAddr; use tokio::net::{TcpListener, TcpStream}; use tower::Service; use tower::ServiceExt; use hyper_util::rt::TokioIo; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] async fn main() { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| { format!("{}=trace,tower_http=debug", env!("CARGO_CRATE_NAME")).into() }), ) .with(tracing_subscriber::fmt::layer()) .init(); let router_svc = Router::new().route("/", get(|| async { "Hello, World!" })); let tower_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 } else { router_svc.oneshot(req).await.map_err(|err| match err {}) } } }); let hyper_service = hyper::service::service_fn(move |request: Request<Incoming>| { tower_service.clone().call(request) }); let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); tracing::debug!("listening on {}", addr); let listener = TcpListener::bind(addr).await.unwrap(); loop { let (stream, _) = listener.accept().await.unwrap(); let io = TokioIo::new(stream); let hyper_service = hyper_service.clone(); tokio::task::spawn(async move { if let Err(err) = http1::Builder::new() .preserve_header_case(true) .title_case_headers(true) .serve_connection(io, hyper_service) .with_upgrades() .await { println!("Failed to serve connection: {err:?}"); } }); } } async fn proxy(req: Request) -> Result<Response, hyper::Error> { tracing::trace!(?req); if let Some(host_addr) = req.uri().authority().map(|auth| auth.to_string()) { tokio::task::spawn(async move { match hyper::upgrade::on(req).await { Ok(upgraded) => { if let Err(e) = tunnel(upgraded, host_addr).await { tracing::warn!("server io error: {}", e); }; } Err(e) => tracing::warn!("upgrade error: {}", e), } }); Ok(Response::new(Body::empty())) } else { tracing::warn!("CONNECT host is not socket addr: {:?}", req.uri()); Ok(( StatusCode::BAD_REQUEST, "CONNECT must be to a socket address", ) .into_response()) } } async fn tunnel(upgraded: Upgraded, addr: String) -> std::io::Result<()> { let mut server = TcpStream::connect(addr).await?; let mut upgraded = TokioIo::new(upgraded); let (from_client, from_server) = tokio::io::copy_bidirectional(&mut upgraded, &mut server).await?; tracing::debug!( "client wrote {} bytes and received {} bytes", from_client, from_server ); Ok(()) }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/handle-head-request/src/main.rs
examples/handle-head-request/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p example-handle-head-request //! ``` use axum::response::{IntoResponse, Response}; use axum::{http, routing::get, Router}; fn app() -> Router { Router::new().route("/get-head", get(get_head_handler)) } #[tokio::main] async fn main() { 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; } // GET routes will also be called for HEAD requests but will have the response body removed. // You can handle the HEAD method explicitly by extracting `http::Method` from the request. async fn get_head_handler(method: http::Method) -> Response { // it usually only makes sense to special-case HEAD // if computing the body has some relevant cost if method == http::Method::HEAD { return ([("x-some-header", "header from HEAD")]).into_response(); } // then do some computing task in GET do_some_computing_task(); ([("x-some-header", "header from GET")], "body from GET").into_response() } fn do_some_computing_task() { // TODO } #[cfg(test)] mod tests { use super::*; use axum::body::Body; use axum::http::{Request, StatusCode}; use http_body_util::BodyExt; use tower::ServiceExt; #[tokio::test] async fn test_get() { let app = app(); let response = app .oneshot(Request::get("/get-head").body(Body::empty()).unwrap()) .await .unwrap(); assert_eq!(response.status(), StatusCode::OK); assert_eq!(response.headers()["x-some-header"], "header from GET"); let body = response.collect().await.unwrap().to_bytes(); assert_eq!(&body[..], b"body from GET"); } #[tokio::test] async fn test_implicit_head() { let app = app(); let response = app .oneshot(Request::head("/get-head").body(Body::empty()).unwrap()) .await .unwrap(); assert_eq!(response.status(), StatusCode::OK); assert_eq!(response.headers()["x-some-header"], "header from HEAD"); let body = response.collect().await.unwrap().to_bytes(); assert!(body.is_empty()); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/global-404-handler/src/main.rs
examples/global-404-handler/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p example-global-404-handler //! ``` use axum::{ http::StatusCode, response::{Html, IntoResponse}, routing::get, Router, }; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] async fn main() { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env() .unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()), ) .with(tracing_subscriber::fmt::layer()) .init(); // build our application with a route let app = Router::new().route("/", get(handler)); // add a fallback service for handling routes to unknown paths let app = app.fallback(handler_404); // 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; } async fn handler() -> Html<&'static str> { Html("<h1>Hello, World!</h1>") } async fn handler_404() -> impl IntoResponse { (StatusCode::NOT_FOUND, "nothing to see here") }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/anyhow-error-response/src/main.rs
examples/anyhow-error-response/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p example-anyhow-error-response //! ``` use axum::{ http::StatusCode, response::{IntoResponse, Response}, routing::get, Router, }; #[tokio::main] async fn main() { let app = app(); 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; } async fn handler() -> Result<(), AppError> { try_thing()?; Ok(()) } fn try_thing() -> Result<(), anyhow::Error> { anyhow::bail!("it failed!") } // Make our own error that wraps `anyhow::Error`. struct AppError(anyhow::Error); // Tell axum how to convert `AppError` into a response. impl IntoResponse for AppError { fn into_response(self) -> Response { ( StatusCode::INTERNAL_SERVER_ERROR, format!("Something went wrong: {}", self.0), ) .into_response() } } fn app() -> Router { Router::new().route("/", get(handler)) } // This enables using `?` on functions that return `Result<_, anyhow::Error>` to turn them into // `Result<_, AppError>`. That way you don't need to do that manually. impl<E> From<E> for AppError where E: Into<anyhow::Error>, { fn from(err: E) -> Self { Self(err.into()) } } #[cfg(test)] mod tests { use super::*; use axum::{body::Body, http::Request, http::StatusCode}; use http_body_util::BodyExt; use tower::ServiceExt; #[tokio::test] async fn test_main_page() { let response = app() .oneshot(Request::builder().uri("/").body(Body::empty()).unwrap()) .await .unwrap(); assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR); let body = response.into_body(); let bytes = body.collect().await.unwrap().to_bytes(); let html = String::from_utf8(bytes.to_vec()).unwrap(); assert_eq!(html, "Something went wrong: it failed!"); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/graceful-shutdown/src/main.rs
examples/graceful-shutdown/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p example-graceful-shutdown //! kill or ctrl-c //! ``` use std::time::Duration; use axum::{routing::get, Router}; use tokio::net::TcpListener; use tokio::signal; use tokio::time::sleep; use tower_http::timeout::TimeoutLayer; use tower_http::trace::TraceLayer; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] async fn main() { // Enable tracing. tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| { format!( "{}=debug,tower_http=debug,axum=trace", env!("CARGO_CRATE_NAME") ) .into() }), ) .with(tracing_subscriber::fmt::layer().without_time()) .init(); // Create a regular axum app. let app = Router::new() .route("/slow", get(|| sleep(Duration::from_secs(5)))) .route("/forever", get(std::future::pending::<()>)) .layer(( TraceLayer::new_for_http(), // Graceful shutdown will wait for outstanding requests to complete. Add a timeout so // requests don't hang forever. TimeoutLayer::new(Duration::from_secs(10)), )); // Create a `TcpListener` using tokio. let listener = TcpListener::bind("0.0.0.0:3000").await.unwrap(); // Run the server with graceful shutdown axum::serve(listener, app) .with_graceful_shutdown(shutdown_signal()) .await; } async fn shutdown_signal() { let ctrl_c = async { signal::ctrl_c() .await .expect("failed to install Ctrl+C handler"); }; #[cfg(unix)] let terminate = async { signal::unix::signal(signal::unix::SignalKind::terminate()) .expect("failed to install signal handler") .recv() .await; }; #[cfg(not(unix))] let terminate = std::future::pending::<()>(); tokio::select! { _ = ctrl_c => {}, _ = terminate => {}, } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/compression/src/tests.rs
examples/compression/src/tests.rs
use assert_json_diff::assert_json_eq; use axum::{ body::{Body, Bytes}, response::Response, }; use brotli::enc::BrotliEncoderParams; use flate2::{read::GzDecoder, write::GzEncoder, Compression}; use http::{header, StatusCode}; use serde_json::{json, Value}; use std::io::{Read, Write}; use tower::ServiceExt; use super::*; #[tokio::test] async fn handle_uncompressed_request_bodies() { // Given let body = json(); let compressed_request = http::Request::post("/") .header(header::CONTENT_TYPE, "application/json") .body(json_body(&body)) .unwrap(); // When let response = app().oneshot(compressed_request).await.unwrap(); // Then assert_eq!(response.status(), StatusCode::OK); assert_json_eq!(json_from_response(response).await, json()); } #[tokio::test] async fn decompress_gzip_request_bodies() { // Given let body = compress_gzip(&json()); let compressed_request = http::Request::post("/") .header(header::CONTENT_TYPE, "application/json") .header(header::CONTENT_ENCODING, "gzip") .body(Body::from(body)) .unwrap(); // When let response = app().oneshot(compressed_request).await.unwrap(); // Then assert_eq!(response.status(), StatusCode::OK); assert_json_eq!(json_from_response(response).await, json()); } #[tokio::test] async fn decompress_br_request_bodies() { // Given let body = compress_br(&json()); let compressed_request = http::Request::post("/") .header(header::CONTENT_TYPE, "application/json") .header(header::CONTENT_ENCODING, "br") .body(Body::from(body)) .unwrap(); // When let response = app().oneshot(compressed_request).await.unwrap(); // Then assert_eq!(response.status(), StatusCode::OK); assert_json_eq!(json_from_response(response).await, json()); } #[tokio::test] async fn decompress_zstd_request_bodies() { // Given let body = compress_zstd(&json()); let compressed_request = http::Request::post("/") .header(header::CONTENT_TYPE, "application/json") .header(header::CONTENT_ENCODING, "zstd") .body(Body::from(body)) .unwrap(); // When let response = app().oneshot(compressed_request).await.unwrap(); // Then assert_eq!(response.status(), StatusCode::OK); assert_json_eq!(json_from_response(response).await, json()); } #[tokio::test] async fn do_not_compress_response_bodies() { // Given let request = http::Request::post("/") .header(header::CONTENT_TYPE, "application/json") .body(json_body(&json())) .unwrap(); // When let response = app().oneshot(request).await.unwrap(); // Then assert_eq!(response.status(), StatusCode::OK); assert_json_eq!(json_from_response(response).await, json()); } #[tokio::test] async fn compress_response_bodies_with_gzip() { // Given let request = http::Request::post("/") .header(header::CONTENT_TYPE, "application/json") .header(header::ACCEPT_ENCODING, "gzip") .body(json_body(&json())) .unwrap(); // When let response = app().oneshot(request).await.unwrap(); // Then assert_eq!(response.status(), StatusCode::OK); let response_body = byte_from_response(response).await; let mut decoder = GzDecoder::new(response_body.as_ref()); let mut decompress_body = String::new(); decoder.read_to_string(&mut decompress_body).unwrap(); assert_json_eq!( serde_json::from_str::<serde_json::Value>(&decompress_body).unwrap(), json() ); } #[tokio::test] async fn compress_response_bodies_with_br() { // Given let request = http::Request::post("/") .header(header::CONTENT_TYPE, "application/json") .header(header::ACCEPT_ENCODING, "br") .body(json_body(&json())) .unwrap(); // When let response = app().oneshot(request).await.unwrap(); // Then assert_eq!(response.status(), StatusCode::OK); let response_body = byte_from_response(response).await; let mut decompress_body = Vec::new(); brotli::BrotliDecompress(&mut response_body.as_ref(), &mut decompress_body).unwrap(); assert_json_eq!( serde_json::from_slice::<serde_json::Value>(&decompress_body).unwrap(), json() ); } #[tokio::test] async fn compress_response_bodies_with_zstd() { // Given let request = http::Request::post("/") .header(header::CONTENT_TYPE, "application/json") .header(header::ACCEPT_ENCODING, "zstd") .body(json_body(&json())) .unwrap(); // When let response = app().oneshot(request).await.unwrap(); // Then assert_eq!(response.status(), StatusCode::OK); let response_body = byte_from_response(response).await; let decompress_body = zstd::stream::decode_all(std::io::Cursor::new(response_body)).unwrap(); assert_json_eq!( serde_json::from_slice::<serde_json::Value>(&decompress_body).unwrap(), json() ); } fn json() -> Value { json!({ "name": "foo", "mainProduct": { "typeId": "product", "id": "p1" }, }) } fn json_body(input: &Value) -> Body { Body::from(serde_json::to_vec(&input).unwrap()) } async fn json_from_response(response: Response) -> Value { let body = byte_from_response(response).await; body_as_json(body) } async fn byte_from_response(response: Response) -> Bytes { axum::body::to_bytes(response.into_body(), usize::MAX) .await .unwrap() } fn body_as_json(body: Bytes) -> Value { serde_json::from_slice(body.as_ref()).unwrap() } fn compress_gzip(json: &Value) -> Vec<u8> { let request_body = serde_json::to_vec(&json).unwrap(); let mut encoder = GzEncoder::new(Vec::new(), Compression::default()); encoder.write_all(&request_body).unwrap(); encoder.finish().unwrap() } fn compress_br(json: &Value) -> Vec<u8> { let request_body = serde_json::to_vec(&json).unwrap(); let mut result = Vec::new(); let params = BrotliEncoderParams::default(); let _ = brotli::enc::BrotliCompress(&mut &request_body[..], &mut result, &params).unwrap(); result } fn compress_zstd(json: &Value) -> Vec<u8> { let request_body = serde_json::to_vec(&json).unwrap(); zstd::stream::encode_all(std::io::Cursor::new(request_body), 4).unwrap() }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/compression/src/main.rs
examples/compression/src/main.rs
use axum::{routing::post, Json, Router}; use serde_json::Value; use tower::ServiceBuilder; use tower_http::{compression::CompressionLayer, decompression::RequestDecompressionLayer}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[cfg(test)] mod tests; #[tokio::main] async fn main() { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env() .unwrap_or_else(|_| format!("{}=trace", env!("CARGO_CRATE_NAME")).into()), ) .with(tracing_subscriber::fmt::layer()) .init(); let app: Router = app(); 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; } fn app() -> Router { Router::new().route("/", post(root)).layer( ServiceBuilder::new() .layer(RequestDecompressionLayer::new()) .layer(CompressionLayer::new()), ) } async fn root(Json(value): Json<Value>) -> Json<Value> { Json(value) }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/templates-minijinja/src/main.rs
examples/templates-minijinja/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p example-templates-minijinja //! ``` //! Demo for the MiniJinja templating engine. //! Exposes three pages all sharing the same layout with a minimal nav menu. use axum::extract::State; use axum::http::StatusCode; use axum::{response::Html, routing::get, Router}; use minijinja::{context, Environment}; use std::sync::Arc; struct AppState { env: Environment<'static>, } #[tokio::main] async fn main() { // init template engine and add templates let mut env = Environment::new(); env.add_template("layout", include_str!("../templates/layout.jinja")) .unwrap(); env.add_template("home", include_str!("../templates/home.jinja")) .unwrap(); env.add_template("content", include_str!("../templates/content.jinja")) .unwrap(); env.add_template("about", include_str!("../templates/about.jinja")) .unwrap(); // pass env to handlers via state let app_state = Arc::new(AppState { env }); // define routes let app = Router::new() .route("/", get(handler_home)) .route("/content", get(handler_content)) .route("/about", get(handler_about)) .with_state(app_state); // run it 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; } async fn handler_home(State(state): State<Arc<AppState>>) -> Result<Html<String>, StatusCode> { let template = state.env.get_template("home").unwrap(); let rendered = template .render(context! { title => "Home", welcome_text => "Hello World!", }) .unwrap(); Ok(Html(rendered)) } async fn handler_content(State(state): State<Arc<AppState>>) -> Result<Html<String>, StatusCode> { let template = state.env.get_template("content").unwrap(); let some_example_entries = vec!["Data 1", "Data 2", "Data 3"]; let rendered = template .render(context! { title => "Content", entries => some_example_entries, }) .unwrap(); Ok(Html(rendered)) } async fn handler_about(State(state): State<Arc<AppState>>) -> Result<Html<String>, StatusCode> { let template = state.env.get_template("about").unwrap(); let rendered = template.render(context!{ title => "About", about_text => "Simple demonstration layout for an axum project with minijinja as templating engine.", }).unwrap(); Ok(Html(rendered)) }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/cors/src/main.rs
examples/cors/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p example-cors //! ``` use axum::{ http::{HeaderValue, Method}, response::{Html, IntoResponse}, routing::get, Json, Router, }; use std::net::SocketAddr; use tower_http::cors::CorsLayer; #[tokio::main] async fn main() { let frontend = async { let app = Router::new().route("/", get(html)); serve(app, 3000).await; }; let backend = async { let app = Router::new().route("/json", get(json)).layer( // see https://docs.rs/tower-http/latest/tower_http/cors/index.html // for more details // // pay attention that for some request types like posting content-type: application/json // it is required to add ".allow_headers([http::header::CONTENT_TYPE])" // or see this issue https://github.com/tokio-rs/axum/issues/849 CorsLayer::new() .allow_origin("http://localhost:3000".parse::<HeaderValue>().unwrap()) .allow_methods([Method::GET]), ); serve(app, 4000).await; }; tokio::join!(frontend, backend); } async fn serve(app: Router, port: u16) { let addr = SocketAddr::from(([127, 0, 0, 1], port)); let listener = tokio::net::TcpListener::bind(addr).await.unwrap(); axum::serve(listener, app).await; } async fn html() -> impl IntoResponse { Html( r#" <script> fetch('http://localhost:4000/json') .then(response => response.json()) .then(data => console.log(data)); </script> "#, ) } async fn json() -> impl IntoResponse { Json(vec!["one", "two", "three"]) }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/customize-extractor-error/src/with_rejection.rs
examples/customize-extractor-error/src/with_rejection.rs
//! Uses `axum_extra::extract::WithRejection` to transform one rejection into //! another //! //! + Easy learning curve: `WithRejection` acts as a wrapper for another //! already existing extractor. You only need to provide a `From` impl //! between the original rejection type and the target rejection. Crates like //! `thiserror` can provide such conversion using derive macros. See //! [`thiserror`] //! - Verbose types: types become much larger, which makes them difficult to //! read. Current limitations on type aliasing makes impossible to destructure //! a type alias. See [#1116] //! //! [`thiserror`]: https://crates.io/crates/thiserror //! [#1116]: https://github.com/tokio-rs/axum/issues/1116#issuecomment-1186197684 use axum::{extract::rejection::JsonRejection, response::IntoResponse, Json}; use axum_extra::extract::WithRejection; use serde_json::{json, Value}; use thiserror::Error; pub async fn handler( // `WithRejection` will extract `Json<Value>` from the request. If it fails, // `JsonRejection` will be transform into `ApiError` and returned as response // to the client. // // The second constructor argument is not meaningful and can be safely ignored WithRejection(Json(value), _): WithRejection<Json<Value>, ApiError>, ) -> impl IntoResponse { Json(dbg!(value)) } // We derive `thiserror::Error` #[derive(Debug, Error)] pub enum ApiError { // The `#[from]` attribute generates `From<JsonRejection> for ApiError` // implementation. See `thiserror` docs for more information #[error(transparent)] JsonExtractorRejection(#[from] JsonRejection), } // We implement `IntoResponse` so ApiError can be used as a response impl IntoResponse for ApiError { fn into_response(self) -> axum::response::Response { let (status, message) = match self { ApiError::JsonExtractorRejection(json_rejection) => { (json_rejection.status(), json_rejection.body_text()) } }; let payload = json!({ "message": message, "origin": "with_rejection" }); (status, Json(payload)).into_response() } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/customize-extractor-error/src/custom_extractor.rs
examples/customize-extractor-error/src/custom_extractor.rs
//! Manual implementation of `FromRequest` that wraps another extractor //! //! + Powerful API: Implementing `FromRequest` grants access to `RequestParts` //! and `async/await`. This means that you can create more powerful rejections //! - Boilerplate: Requires creating a new extractor for every custom rejection //! - Complexity: Manually implementing `FromRequest` results on more complex code use axum::{ extract::{rejection::JsonRejection, FromRequest, MatchedPath, Request}, http::StatusCode, response::IntoResponse, RequestPartsExt, }; use serde_json::{json, Value}; pub async fn handler(Json(value): Json<Value>) -> impl IntoResponse { Json(dbg!(value)); } // We define our own `Json` extractor that customizes the error from `axum::Json` pub struct Json<T>(pub T); impl<S, T> FromRequest<S> for Json<T> where axum::Json<T>: FromRequest<S, Rejection = JsonRejection>, S: Send + Sync, { type Rejection = (StatusCode, axum::Json<Value>); async fn from_request(req: Request, state: &S) -> Result<Self, Self::Rejection> { let (mut parts, body) = req.into_parts(); // We can use other extractors to provide better rejection messages. // For example, here we are using `axum::extract::MatchedPath` to // provide a better error message. // // Have to run that first since `Json` extraction consumes the request. let path = parts .extract::<MatchedPath>() .await .map(|path| path.as_str().to_owned()) .ok(); let req = Request::from_parts(parts, body); match axum::Json::<T>::from_request(req, state).await { Ok(value) => Ok(Self(value.0)), // convert the error from `axum::Json` into whatever we want Err(rejection) => { let payload = json!({ "message": rejection.body_text(), "origin": "custom_extractor", "path": path, }); Err((rejection.status(), axum::Json(payload))) } } } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/customize-extractor-error/src/derive_from_request.rs
examples/customize-extractor-error/src/derive_from_request.rs
//! Uses `axum::extract::FromRequest` to wrap another extractor and customize the //! rejection //! //! + Easy learning curve: Deriving `FromRequest` generates a `FromRequest` //! implementation for your type using another extractor. You only need //! to provide a `From` impl between the original rejection type and the //! target rejection. Crates like [`thiserror`] can provide such conversion //! using derive macros. //! - Boilerplate: Requires deriving `FromRequest` for every custom rejection //! - There are some known limitations: [FromRequest#known-limitations] //! //! [`thiserror`]: https://crates.io/crates/thiserror //! [FromRequest#known-limitations]: https://docs.rs/axum-macros/*/axum_macros/derive.FromRequest.html#known-limitations use axum::{ extract::rejection::JsonRejection, extract::FromRequest, http::StatusCode, response::IntoResponse, }; use serde::Serialize; use serde_json::{json, Value}; pub async fn handler(Json(value): Json<Value>) -> impl IntoResponse { Json(dbg!(value)) } // create an extractor that internally uses `axum::Json` but has a custom rejection #[derive(FromRequest)] #[from_request(via(axum::Json), rejection(ApiError))] pub struct Json<T>(T); // We implement `IntoResponse` for our extractor so it can be used as a response impl<T: Serialize> IntoResponse for Json<T> { fn into_response(self) -> axum::response::Response { let Self(value) = self; axum::Json(value).into_response() } } // We create our own rejection type #[derive(Debug)] pub struct ApiError { status: StatusCode, message: String, } // We implement `From<JsonRejection> for ApiError` impl From<JsonRejection> for ApiError { fn from(rejection: JsonRejection) -> Self { Self { status: rejection.status(), message: rejection.body_text(), } } } // We implement `IntoResponse` so `ApiError` can be used as a response impl IntoResponse for ApiError { fn into_response(self) -> axum::response::Response { let payload = json!({ "message": self.message, "origin": "derive_from_request" }); (self.status, axum::Json(payload)).into_response() } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/customize-extractor-error/src/main.rs
examples/customize-extractor-error/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p example-customize-extractor-error //! ``` mod custom_extractor; mod derive_from_request; mod with_rejection; use axum::{routing::post, Router}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] async fn main() { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env() .unwrap_or_else(|_| format!("{}=trace", env!("CARGO_CRATE_NAME")).into()), ) .with(tracing_subscriber::fmt::layer()) .init(); // Build our application with some routes let app = Router::new() .route("/with-rejection", post(with_rejection::handler)) .route("/custom-extractor", post(custom_extractor::handler)) .route("/derive-from-request", post(derive_from_request::handler)); // Run our application 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; }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/reverse-proxy/src/main.rs
examples/reverse-proxy/src/main.rs
//! Reverse proxy listening in "localhost:4000" will proxy all requests to "localhost:3000" //! endpoint. //! //! Run with //! //! ```not_rust //! cargo run -p example-reverse-proxy //! ``` use axum::{ body::Body, extract::{Request, State}, http::uri::Uri, response::{IntoResponse, Response}, routing::get, Router, }; use hyper::StatusCode; use hyper_util::{client::legacy::connect::HttpConnector, rt::TokioExecutor}; type Client = hyper_util::client::legacy::Client<HttpConnector, Body>; #[tokio::main] async fn main() { tokio::spawn(server()); let client: Client = hyper_util::client::legacy::Client::<(), ()>::builder(TokioExecutor::new()) .build(HttpConnector::new()); let app = Router::new().route("/", get(handler)).with_state(client); 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; } async fn handler(State(client): State<Client>, mut req: Request) -> Result<Response, StatusCode> { let path = req.uri().path(); let path_query = req .uri() .path_and_query() .map(|v| v.as_str()) .unwrap_or(path); let uri = format!("http://127.0.0.1:3000{path_query}"); *req.uri_mut() = Uri::try_from(uri).unwrap(); Ok(client .request(req) .await .map_err(|_| StatusCode::BAD_REQUEST)? .into_response()) } async fn server() { let app = Router::new().route("/", get(|| async { "Hello, world!" })); 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; }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/hello-world/src/main.rs
examples/hello-world/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p example-hello-world //! ``` use axum::{response::Html, routing::get, Router}; #[tokio::main] async fn main() { // build our application with a route let app = Router::new().route("/", get(handler)); // run it 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; } async fn handler() -> Html<&'static str> { Html("<h1>Hello, World!</h1>") }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/jwt/src/main.rs
examples/jwt/src/main.rs
//! Example JWT authorization/authentication. //! //! Run with //! //! ```not_rust //! JWT_SECRET=secret cargo run -p example-jwt //! ``` use axum::{ 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 serde::{Deserialize, Serialize}; use serde_json::json; use std::fmt::Display; use std::sync::LazyLock; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; // Quick instructions // // - get an authorization token: // // curl -s \ // -w '\n' \ // -H 'Content-Type: application/json' \ // -d '{"client_id":"foo","client_secret":"bar"}' \ // http://localhost:3000/authorize // // - visit the protected area using the authorized token // // curl -s \ // -w '\n' \ // -H 'Content-Type: application/json' \ // -H 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJiQGIuY29tIiwiY29tcGFueSI6IkFDTUUiLCJleHAiOjEwMDAwMDAwMDAwfQ.M3LAZmrzUkXDC1q5mSzFAs_kJrwuKz3jOoDmjJ0G4gM' \ // http://localhost:3000/protected // // - try to visit the protected area using an invalid token // // curl -s \ // -w '\n' \ // -H 'Content-Type: application/json' \ // -H 'Authorization: Bearer blahblahblah' \ // http://localhost:3000/protected static KEYS: LazyLock<Keys> = LazyLock::new(|| { let secret = std::env::var("JWT_SECRET").expect("JWT_SECRET must be set"); Keys::new(secret.as_bytes()) }); #[tokio::main] async fn main() { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env() .unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()), ) .with(tracing_subscriber::fmt::layer()) .init(); let app = Router::new() .route("/protected", get(protected)) .route("/authorize", post(authorize)); 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; } async fn protected(claims: Claims) -> Result<String, AuthError> { // Send the protected data to the user Ok(format!( "Welcome to the protected area :)\nYour data:\n{claims}", )) } async fn authorize(Json(payload): Json<AuthPayload>) -> Result<Json<AuthBody>, AuthError> { // Check if the user sent the credentials if payload.client_id.is_empty() || payload.client_secret.is_empty() { return Err(AuthError::MissingCredentials); } // Here you can check the user credentials from a database if payload.client_id != "foo" || payload.client_secret != "bar" { return Err(AuthError::WrongCredentials); } let claims = Claims { sub: "b@b.com".to_owned(), company: "ACME".to_owned(), // Mandatory expiry time as UTC timestamp exp: 2000000000, // May 2033 }; // Create the authorization token let token = encode(&Header::default(), &claims, &KEYS.encoding) .map_err(|_| AuthError::TokenCreation)?; // Send the authorized token Ok(Json(AuthBody::new(token))) } impl Display for Claims { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, "Email: {}\nCompany: {}", self.sub, self.company) } } impl AuthBody { fn new(access_token: String) -> Self { Self { access_token, token_type: "Bearer".to_string(), } } } impl<S> FromRequestParts<S> for Claims where S: Send + Sync, { type Rejection = AuthError; async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> { // Extract the token from the authorization header let TypedHeader(Authorization(bearer)) = parts .extract::<TypedHeader<Authorization<Bearer>>>() .await .map_err(|_| AuthError::InvalidToken)?; // Decode the user data let token_data = decode::<Claims>(bearer.token(), &KEYS.decoding, &Validation::default()) .map_err(|_| AuthError::InvalidToken)?; Ok(token_data.claims) } } impl IntoResponse for AuthError { fn into_response(self) -> Response { let (status, error_message) = match self { AuthError::WrongCredentials => (StatusCode::UNAUTHORIZED, "Wrong credentials"), AuthError::MissingCredentials => (StatusCode::BAD_REQUEST, "Missing credentials"), AuthError::TokenCreation => (StatusCode::INTERNAL_SERVER_ERROR, "Token creation error"), AuthError::InvalidToken => (StatusCode::BAD_REQUEST, "Invalid token"), }; let body = Json(json!({ "error": error_message, })); (status, body).into_response() } } struct Keys { encoding: EncodingKey, decoding: DecodingKey, } impl Keys { fn new(secret: &[u8]) -> Self { Self { encoding: EncodingKey::from_secret(secret), decoding: DecodingKey::from_secret(secret), } } } #[derive(Debug, Clone, Serialize, Deserialize)] struct Claims { sub: String, company: String, exp: usize, } #[derive(Debug, Serialize)] struct AuthBody { access_token: String, token_type: String, } #[derive(Debug, Deserialize)] struct AuthPayload { client_id: String, client_secret: String, } #[derive(Debug)] enum AuthError { WrongCredentials, MissingCredentials, TokenCreation, InvalidToken, }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/auto-reload/src/main.rs
examples/auto-reload/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p auto-reload //! ``` use axum::{response::Html, routing::get, Router}; use listenfd::ListenFd; use tokio::net::TcpListener; #[tokio::main] async fn main() { // build our application with a route let app = Router::new().route("/", get(handler)); let mut listenfd = ListenFd::from_env(); let listener = match listenfd.take_tcp_listener(0).unwrap() { // if we are given a tcp listener on listen fd 0, we use that one Some(listener) => { listener.set_nonblocking(true).unwrap(); TcpListener::from_std(listener).unwrap() } // otherwise fall back to local listening None => TcpListener::bind("127.0.0.1:3000").await.unwrap(), }; // run it println!("listening on {}", listener.local_addr().unwrap()); axum::serve(listener, app).await; } async fn handler() -> Html<&'static str> { Html("<h1>Hello, World!</h1>") }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/multipart-form/src/main.rs
examples/multipart-form/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p example-multipart-form //! ``` use axum::{ extract::{DefaultBodyLimit, Multipart}, response::Html, routing::get, Router, }; use tower_http::limit::RequestBodyLimitLayer; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] async fn main() { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| { format!("{}=debug,tower_http=debug", env!("CARGO_CRATE_NAME")).into() }), ) .with(tracing_subscriber::fmt::layer()) .init(); // build our application with some routes let app = Router::new() .route("/", get(show_form).post(accept_form)) .layer(DefaultBodyLimit::disable()) .layer(RequestBodyLimitLayer::new( 250 * 1024 * 1024, /* 250mb */ )) .layer(tower_http::trace::TraceLayer::new_for_http()); // run it with hyper 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; } async fn show_form() -> Html<&'static str> { Html( r#" <!doctype html> <html> <head></head> <body> <form action="/" method="post" enctype="multipart/form-data"> <label> Upload file: <input type="file" name="file" multiple> </label> <input type="submit" value="Upload files"> </form> </body> </html> "#, ) } async fn accept_form(mut multipart: Multipart) { while let Some(field) = multipart.next_field().await.unwrap() { let name = field.name().unwrap().to_string(); let file_name = field.file_name().unwrap().to_string(); let content_type = field.content_type().unwrap().to_string(); let data = field.bytes().await.unwrap(); println!( "Length of `{name}` (`{file_name}`: `{content_type}`) is {} bytes", data.len() ); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/static-file-server/src/main.rs
examples/static-file-server/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p example-static-file-server //! ``` use axum::{ extract::Request, handler::HandlerWithoutStateExt, http::StatusCode, routing::get, Router, }; use std::net::SocketAddr; use tower::ServiceExt; use tower_http::{ services::{ServeDir, ServeFile}, trace::TraceLayer, }; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; #[tokio::main] async fn main() { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| { format!("{}=debug,tower_http=debug", env!("CARGO_CRATE_NAME")).into() }), ) .with(tracing_subscriber::fmt::layer()) .init(); tokio::join!( serve(using_serve_dir(), 3001), serve(using_serve_dir_with_assets_fallback(), 3002), serve(using_serve_dir_only_from_root_via_fallback(), 3003), serve(using_serve_dir_with_handler_as_service(), 3004), serve(two_serve_dirs(), 3005), serve(calling_serve_dir_from_a_handler(), 3006), serve(using_serve_file_from_a_route(), 3307), ); } fn using_serve_dir() -> Router { // serve the file in the "assets" directory under `/assets` Router::new().nest_service("/assets", ServeDir::new("assets")) } fn using_serve_dir_with_assets_fallback() -> Router { // `ServeDir` allows setting a fallback if an asset is not found // so with this `GET /assets/doesnt-exist.jpg` will return `index.html` // rather than a 404 let serve_dir = ServeDir::new("assets").not_found_service(ServeFile::new("assets/index.html")); Router::new() .route("/foo", get(|| async { "Hi from /foo" })) .nest_service("/assets", serve_dir.clone()) .fallback_service(serve_dir) } fn using_serve_dir_only_from_root_via_fallback() -> Router { // you can also serve the assets directly from the root (not nested under `/assets`) // by only setting a `ServeDir` as the fallback let serve_dir = ServeDir::new("assets").not_found_service(ServeFile::new("assets/index.html")); Router::new() .route("/foo", get(|| async { "Hi from /foo" })) .fallback_service(serve_dir) } fn using_serve_dir_with_handler_as_service() -> Router { async fn handle_404() -> (StatusCode, &'static str) { (StatusCode::NOT_FOUND, "Not found") } // 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" })) .fallback_service(serve_dir) } fn two_serve_dirs() -> Router { // you can also have two `ServeDir`s nested at different paths let serve_dir_from_assets = ServeDir::new("assets"); let serve_dir_from_dist = ServeDir::new("dist"); Router::new() .nest_service("/assets", serve_dir_from_assets) .nest_service("/dist", serve_dir_from_dist) } #[allow(clippy::let_and_return)] fn calling_serve_dir_from_a_handler() -> Router { // via `tower::Service::call`, or more conveniently `tower::ServiceExt::oneshot` you can // call `ServeDir` yourself from a handler Router::new().nest_service( "/foo", get(|request: Request| async { let service = ServeDir::new("assets"); let result = service.oneshot(request).await; result }), ) } fn using_serve_file_from_a_route() -> Router { Router::new().route_service("/foo", ServeFile::new("assets/index.html")) } async fn serve(app: Router, port: u16) { let addr = SocketAddr::from(([127, 0, 0, 1], port)); 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; }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/sse/src/main.rs
examples/sse/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p example-sse //! ``` //! Test with //! ```not_rust //! cargo test -p example-sse //! ``` use axum::{ response::sse::{Event, Sse}, routing::get, Router, }; use axum_extra::TypedHeader; use futures_util::stream::{self, Stream}; 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}; #[tokio::main] async fn main() { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| { format!("{}=debug,tower_http=debug", env!("CARGO_CRATE_NAME")).into() }), ) .with(tracing_subscriber::fmt::layer()) .init(); // build our application let app = app(); // 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; } fn app() -> Router { let assets_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("assets"); let static_files_service = ServeDir::new(assets_dir).append_index_html_on_directories(true); // build our application with a route Router::new() .fallback_service(static_files_service) .route("/sse", get(sse_handler)) .layer(TraceLayer::new_for_http()) } async fn sse_handler( TypedHeader(user_agent): TypedHeader<headers::UserAgent>, ) -> Sse<impl Stream<Item = Result<Event, Infallible>>> { println!("`{}` connected", user_agent.as_str()); // A `Stream` that repeats an event every second // // You can also create streams from tokio channels using the wrappers in // https://docs.rs/tokio-stream let stream = stream::repeat_with(|| Event::default().data("hi!")) .map(Ok) .throttle(Duration::from_secs(1)); Sse::new(stream).keep_alive( axum::response::sse::KeepAlive::new() .interval(Duration::from_secs(1)) .text("keep-alive-text"), ) } #[cfg(test)] mod tests { use eventsource_stream::Eventsource; use tokio::net::TcpListener; use super::*; #[tokio::test] async fn integration_test() { // A helper function that spawns our application in the background async fn spawn_app(host: impl Into<String>) -> String { let host = host.into(); // Bind to localhost at the port 0, which will let the OS assign an available port to us let listener = TcpListener::bind(format!("{host}:0")).await.unwrap(); // Retrieve the port assigned to us by the OS let port = listener.local_addr().unwrap().port(); tokio::spawn(async { axum::serve(listener, app()).await; }); // Returns address (e.g. http://127.0.0.1{random_port}) format!("http://{host}:{port}") } let listening_url = spawn_app("127.0.0.1").await; let mut event_stream = reqwest::Client::new() .get(format!("{listening_url}/sse")) .header("User-Agent", "integration_test") .send() .await .unwrap() .bytes_stream() .eventsource() .take(1); let mut event_data: Vec<String> = vec![]; while let Some(event) = event_stream.next().await { match event { Ok(event) => { // break the loop at the end of SSE stream if event.data == "[DONE]" { break; } event_data.push(event.data); } Err(_) => { panic!("Error in event stream"); } } } assert!(event_data[0] == "hi!"); } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/readme/src/main.rs
examples/readme/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p example-readme //! ``` use axum::{ http::StatusCode, response::IntoResponse, routing::{get, post}, Json, Router, }; use serde::{Deserialize, Serialize}; #[tokio::main] async fn main() { // initialize tracing tracing_subscriber::fmt::init(); // build our application with a route let app = Router::new() // `GET /` goes to `root` .route("/", get(root)) // `POST /users` goes to `create_user` .route("/users", post(create_user)); // run our app with hyper 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; } // basic handler that responds with a static string async fn root() -> &'static str { "Hello, World!" } async fn create_user( // this argument tells axum to parse the request body // as JSON into a `CreateUser` type Json(payload): Json<CreateUser>, ) -> impl IntoResponse { // insert your application logic here let user = User { id: 1337, username: payload.username, }; // this will be converted into a JSON response // with a status code of `201 Created` (StatusCode::CREATED, Json(user)) } // the input to our `create_user` handler #[derive(Deserialize)] struct CreateUser { username: String, } // the output to our `create_user` handler #[derive(Serialize)] struct User { id: u64, username: String, }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/examples/diesel-postgres/src/main.rs
examples/diesel-postgres/src/main.rs
//! Run with //! //! ```not_rust //! cargo run -p example-diesel-postgres //! ``` //! //! Checkout the [diesel webpage](https://diesel.rs) for //! longer guides about diesel //! //! Checkout the [crates.io source code](https://github.com/rust-lang/crates.io/) //! for a real world application using axum and diesel use axum::{ extract::State, http::StatusCode, response::Json, routing::{get, post}, Router, }; use diesel::prelude::*; use diesel_migrations::{embed_migrations, EmbeddedMigrations, MigrationHarness}; use std::net::SocketAddr; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; // this embeds the migrations into the application binary // the migration path is relative to the `CARGO_MANIFEST_DIR` pub const MIGRATIONS: EmbeddedMigrations = embed_migrations!("migrations/"); // normally part of your generated schema.rs file table! { users (id) { id -> Integer, name -> Text, hair_color -> Nullable<Text>, } } #[derive(serde::Serialize, HasQuery)] struct User { id: i32, name: String, hair_color: Option<String>, } #[derive(serde::Deserialize, Insertable)] #[diesel(table_name = users)] struct NewUser { name: String, hair_color: Option<String>, } #[tokio::main] async fn main() { tracing_subscriber::registry() .with( tracing_subscriber::EnvFilter::try_from_default_env() .unwrap_or_else(|_| format!("{}=debug", env!("CARGO_CRATE_NAME")).into()), ) .with(tracing_subscriber::fmt::layer()) .init(); let db_url = std::env::var("DATABASE_URL").unwrap(); // set up connection pool let manager = deadpool_diesel::postgres::Manager::new(db_url, deadpool_diesel::Runtime::Tokio1); let pool = deadpool_diesel::postgres::Pool::builder(manager) .build() .unwrap(); // run the migrations on server startup { let conn = pool.get().await.unwrap(); conn.interact(|conn| conn.run_pending_migrations(MIGRATIONS).map(|_| ())) .await .unwrap() .unwrap(); } // build our application with some routes let app = Router::new() .route("/user/list", get(list_users)) .route("/user/create", post(create_user)) .with_state(pool); // run it with hyper let addr = SocketAddr::from(([127, 0, 0, 1], 3000)); tracing::debug!("listening on {addr}"); let listener = tokio::net::TcpListener::bind(addr).await.unwrap(); axum::serve(listener, app).await; } async fn create_user( State(pool): State<deadpool_diesel::postgres::Pool>, Json(new_user): Json<NewUser>, ) -> Result<Json<User>, (StatusCode, String)> { let conn = pool.get().await.map_err(internal_error)?; let res = conn .interact(|conn| { diesel::insert_into(users::table) .values(new_user) .returning(User::as_returning()) .get_result(conn) }) .await .map_err(internal_error)? .map_err(internal_error)?; Ok(Json(res)) } async fn list_users( State(pool): State<deadpool_diesel::postgres::Pool>, ) -> Result<Json<Vec<User>>, (StatusCode, String)> { let conn = pool.get().await.map_err(internal_error)?; let res = conn .interact(|conn| User::query().load(conn)) .await .map_err(internal_error)? .map_err(internal_error)?; Ok(Json(res)) } /// Utility function for mapping any error into a `500 Internal Server Error` /// response. fn internal_error<E>(err: E) -> (StatusCode, String) where E: std::error::Error, { (StatusCode::INTERNAL_SERVER_ERROR, err.to_string()) }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false