Function axum::middleware::from_fn_with_state
source · pub fn from_fn_with_state<F, S, T>(state: S, f: F) -> FromFnLayer<F, S, T>
Expand description
Create a middleware from an async function with the given state.
See State
for more details about accessing state.
§Example
use axum::{
Router,
http::{Request, StatusCode},
routing::get,
response::{IntoResponse, Response},
middleware::{self, Next},
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>,
next: Next<B>,
) -> Response {
// do something with `request`...
let response = next.run(request).await;
// do something with `response`...
response
}
let state = AppState { /* ... */ };
let app = Router::new()
.route("/", get(|| async { /* ... */ }))
.route_layer(middleware::from_fn_with_state(state.clone(), my_middleware))
.with_state(state);