expression
Axum: middleware with from_fn
Middleware surrounds a handler, so shared behavior can happen before and after the handler without duplicating code in every endpoint. Next passes ownership of the request onward and returns the resulting response. In-memory standalone Cargo example. Expected stdout (not executed): before handler after 200 Common mistake: Forgetting to call Next when the request should continue.
Formal Syntax & Structure
rust syntaxrust
middleware::from_fn(function)Working Example
Example Snippetrust
use axum::{Router, body::{Body, to_bytes}, http::{Request, StatusCode}};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() { use axum::{routing::get, middleware::{self, Next}, response::Response}; async fn trace(req: axum::extract::Request, next: Next) -> Response { println!("before"); let res = next.run(req).await; println!("after"); res } let app = Router::new().route("/", get(|| async { println!("handler"); "ok" })).layer(middleware::from_fn(trace)); let r = app.oneshot(Request::new(Body::empty())).await.unwrap(); println!("{}", r.status().as_u16());}