expression
Axum: inject shared configuration
Router state supplies application-wide configuration to handlers. State is not a request-specific identity. Cloneable state may contain shared handles; copying a configuration value is sufficient for this small example. In-memory standalone Cargo example. No socket is opened. Expected stdout (not executed): demo Common mistake: Using global router state to store the current authenticated user.
Formal Syntax & Structure
rust syntaxrust
Router::with_state(value); State(value): State<AppState>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::{extract::State, routing::get}; #[derive(Clone)] struct Config { label: String } async fn info(State(c): State<Config>) -> String { c.label } let app: Router = Router::new().route("/info", get(info)).with_state(Config { label: "demo".into() }); let r = app.oneshot(Request::builder().uri("/info").body(Body::empty()).unwrap()).await.unwrap(); println!("{}", std::str::from_utf8(&to_bytes(r.into_body(), 64).await.unwrap()).unwrap());}