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
    req: Request<B>,
    next: Next<B>,
) -> Response {
    // do something with `req`...
    let res = next.run(req).await;
    // do something with `res`...
    res
}

let state = AppState { /* ... */ };

let app = Router::with_state(state.clone())
    .route("/", get(|| async { /* ... */ }))
    .route_layer(middleware::from_fn_with_state(state, my_middleware));