Rust

axum with Shared State + Extractors

admin by @admin ADMIN
5h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Use `State` to inject shared application state (DB pool, config, etc.) into every handler. `Path` and `Json` extractors deserialize URL params and request bodies for you.
Rust
Raw
use axum::{
    extract::{Path, State},
    routing::{get, post},
    Json, Router,
};
use serde::{Deserialize, Serialize};
use std::sync::{Arc, Mutex};

#[derive(Clone)]
struct AppState {
    counter: Arc<Mutex<u64>>,
}

#[derive(Deserialize)]
struct NewItem { name: String }

#[derive(Serialize)]
struct Item { id: u64, name: String }

async fn get_count(State(state): State<AppState>) -> Json<u64> {
    Json(*state.counter.lock().unwrap())
}

async fn create_item(
    State(state): State<AppState>,
    Json(payload): Json<NewItem>,
) -> Json<Item> {
    let mut id = state.counter.lock().unwrap();
    *id += 1;
    Json(Item { id: *id, name: payload.name })
}

async fn show_item(Path(id): Path<u64>) -> String {
    format!("item {id}")
}

#[tokio::main]
async fn main() {
    let state = AppState { counter: Arc::new(Mutex::new(0)) };
    let app = Router::new()
        .route("/count",        get(get_count))
        .route("/items",        post(create_item))
        .route("/items/{id}",   get(show_item))
        .with_state(state);
    // ... bind + serve as in the hello-world example ...
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.