// Created on savesnippets.com ยท https://savesnippets.com/2iGbqFFx5dr1kX 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>, } #[derive(Deserialize)] struct NewItem { name: String } #[derive(Serialize)] struct Item { id: u64, name: String } async fn get_count(State(state): State) -> Json { Json(*state.counter.lock().unwrap()) } async fn create_item( State(state): State, Json(payload): Json, ) -> Json { let mut id = state.counter.lock().unwrap(); *id += 1; Json(Item { id: *id, name: payload.name }) } async fn show_item(Path(id): Path) -> 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 ... }