Function axum::middleware::map_request_with_state
source · pub fn map_request_with_state<F, S, T>(
state: S,
f: F,
) -> MapRequestLayer<F, S, T>
Expand description
Create a middleware from an async function that transforms a request, with the given state.
See State
for more details about accessing state.
§Example
use axum::{
Router,
http::{Request, StatusCode},
routing::get,
response::IntoResponse,
middleware::map_request_with_state,
extract::State,
};
#[derive(Clone)]
struct AppState { /* ... */ }
async fn my_middleware<B>(
State(state): State<AppState>,
// you can add more extractors here but the last
// extractor must implement `FromRequest` which
// `Request` does
request: Request<B>,
) -> Request<B> {
// do something with `state` and `request`...
request
}
let state = AppState { /* ... */ };
let app = Router::new()
.route("/", get(|| async { /* ... */ }))
.route_layer(map_request_with_state(state.clone(), my_middleware))
.with_state(state);