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 ...
}
Create a free account and build your private vault. Share publicly whenever you want.