expression

Axum: optional request extensions

An optional Extension lets the handler distinguish missing context from present context. A required extension missing at runtime is normally a server configuration error. Optional context must not turn a required authorization check into an allow-by-default path. In-memory standalone Cargo example. Expected stdout (not executed): none configured Common mistake: Treating missing authorization metadata as an anonymous success without policy.

Formal Syntax & Structure

rust syntaxrust
Option<Extension<T>>

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::{Extension, routing::get};    #[derive(Clone)] struct Label(&'static str);    async fn show(label: Option<Extension<Label>>) -> &'static str {        label.map(|Extension(x)| x.0).unwrap_or("none")    }    let app = Router::new().route("/", get(show));    for router in [app.clone(), app.layer(Extension(Label("configured")))] {        let r = router.oneshot(Request::new(Body::empty())).await.unwrap();        println!("{}", std::str::from_utf8(&to_bytes(r.into_body(), 32).await.unwrap()).unwrap());    }}
Rust Reference