Use Router::layer to apply middleware to all routes or route_layer to apply it to specific routes.
use axum::{routing::get, Router};
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(|| async { "Hello" }))
.layer(axum::middleware::from_fn(my_middleware));
axum::serve(
tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(),
app.into_make_service(),
)
.await
.unwrap();
}
async fn my_middleware<B>(
req: axum::extract::Request,
next: axum::middleware::Next<B>,
) -> axum::response::Response {
let res = next.run(req).await;
res
}