Rust HTTP Server with Axum
Build a type-safe HTTP server in Rust using Axum with extractors, JSON responses, error handling, and state sharing. Includes route definitions, middleware.
Code
use axum::{
extract::State,
http::StatusCode,
response::Json,
routing::get,
Router,
};
use serde_json::{json, Value};
use std::sync::Arc;
struct AppState {
db: String,
}
async fn health() -> &'static str {
"OK"
}
async fn get_data(State(state): State<Arc<AppState>>) -> Result<Json<Value>, StatusCode> {
Ok(Json(json!({"db": state.db, "data": []})))
}
#[tokio::main]
async fn main() {
let state = Arc::new(AppState { db: "postgres".into() });
let app = Router::new()
.route("/health", get(health))
.route("/api/data", get(get_data))
.with_state(state);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}