How do I access state in middleware without redefining state? #1912
-
I need my database pool in most of my auth middleware, but I don't want to recreate my state for each My state.rs file use axum::extract::FromRef;
use bdata::db::Pool;
#[derive(Clone)]
pub struct AppState {
pub pool: Pool,
}
impl FromRef<AppState> for Pool {
fn from_ref(app_state: &AppState) -> Pool {
app_state.pool.clone()
}
} The end of my main.rs file ...
let app = routes.with_state(app_state);
axum::Server::bind(&"0.0.0.0:8000".parse().unwrap())
.serve(app.into_make_service())
.await
.unwrap(); A router file pub fn configure() -> Router<AppState> {
Router::<_>::new()
.route("/test", get(routes_v1::test))
.route_layer(axum::middleware::from_fn(middleware::session_user::auth)) // This errors with:
}
// `axum::middleware::FromFn<fn(axum::extract::State<Pool<ConnectionManager<diesel::MysqlConnection>>>, http::Request<_>, Next<_>) -> impl std::future::Future<Output = Result<http::Response<http_body::combinators::box_body::UnsyncBoxBody<axum::body::Bytes, axum::Error>>, http::StatusCode>> {session_user::auth::<_>}, (), Route, _>: Service<http::Request<hyper::Body>>` is not satisfied
The abbreviated session user middleware: pub async fn auth<B>(State(pool): State<Pool>, mut req: Request<B>, next: Next<B>) -> Result<Response, StatusCode> {
let session_dao = &mut SessionDao::new(&pool);
let user_dao = &mut UserDao::new(&pool);
...
req.extensions_mut().insert(SessionUser(user));
Ok(next.run(req).await) |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 12 replies
-
Do I need to pass a clone of the state through to each router configuration function? Would you recommend using Arc instead of cloning the database ool? |
Beta Was this translation helpful? Give feedback.
-
We document the options here https://docs.rs/axum/latest/axum/middleware/index.html#accessing-state-in-middleware |
Beta Was this translation helpful? Give feedback.
We document the options here https://docs.rs/axum/latest/axum/middleware/index.html#accessing-state-in-middleware