expression
Axum: return early from middleware
Middleware can reject a request before the handler runs. This teaching gate checks a synthetic workflow header, not a credential; callers can freely set it. Real authorization requires a verified principal and server-side policy. In-memory standalone Cargo example. Expected stdout (not executed): 400 handler ran 200 Common mistake: Using an arbitrary client header as proof of identity.
Formal Syntax & Structure
rust syntaxrust
if condition { return response; }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, IntoResponse}}; async fn gate(req: axum::extract::Request, next: Next) -> Response { if req.headers().get("x-demo-mode").and_then(|v| v.to_str().ok()) != Some("enabled") { return StatusCode::BAD_REQUEST.into_response(); } next.run(req).await } let app = Router::new().route("/", get(|| async { println!("handler ran"); "ok" })).layer(middleware::from_fn(gate)); for enabled in [false, true] { let mut b = Request::builder().uri("/"); if enabled { b = b.header("x-demo-mode", "enabled"); } let r = app.clone().oneshot(b.body(Body::empty()).unwrap()).await.unwrap(); println!("{}", r.status().as_u16()); }}