引言
Axum 基于 Tower 和 Hyper,类型安全且组合性强。它的提取器把请求解析为类型,错误可以在编译期被约束。
路由与提取器
用 Router::new().route("/orders/:id", get(handler)) 注册路由。Path<T>、Query<T> 和 Json<T> 提取器自动解析并返回 400/422。用 State 注入共享依赖。
状态与错误
共享状态使用 Arc,不要在跨 .await 时持有 MutexGuard;需要异步锁时使用 tokio::sync::Mutex。定义实现 IntoResponse 的错误类型,返回稳定的 JSON 错误和状态码,避免泄露内部细节。
中间件与关闭
用 tower_http 添加 tracing、超时和请求体限制。监听 SIGTERM 后调用 axum::serve(...).with_graceful_shutdown(...),等待进行中请求完成。
测试
用 tower::ServiceExt::oneshot 直接调用 router,断言状态码、JSON 和头,无需绑定端口。测试提取失败、授权拒绝和超时。
代码示例
[package]
name = "axum-api"
version = "0.1.0"
edition = "2021"
[dependencies]
axum = "0.8"
tokio = { version = "1", features = ["macros", "rt-multi-thread", "signal"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
tower = "0.5"
tower-http = { version = "0.6", features = ["trace", "timeout"] }
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
thiserror = "2"
use axum::{routing::{get, post}, Router};
pub fn app() -> Router {
Router::new()
.route("/health", get(health))
.route("/users/{id}", get(get_user))
}
async fn health() -> &'static str {
"OK"
}
use axum::{extract::{Path, State}, Json};
use serde::{Deserialize, Serialize};
use std::{collections::HashMap, sync::Arc};
use tokio::sync::RwLock;
#[derive(Clone)]
pub struct AppState {
pub users: Arc<RwLock<HashMap<u32, User>>>,
}
#[derive(Clone, Serialize)]
pub struct User {
pub id: u32,
pub name: String,
}
#[derive(Deserialize)]
pub struct CreateUser {
pub name: String,
}
pub async fn get_user(
Path(id): Path<u32>,
State(state): State<AppState>,
) -> Result<Json<User>, AppError> {
let users = state.users.read().await;
let user = users.get(&id).cloned().ok_or(AppError::NotFound)?;
Ok(Json(user))
}
pub async fn create_user(
State(state): State<AppState>,
Json(input): Json<CreateUser>,
) -> Result<(axum::http::StatusCode, Json<User>), AppError> {
if input.name.trim().is_empty() {
return Err(AppError::Validation("name is required".into()));
}
let mut users = state.users.write().await;
let id = users.len() as u32 + 1;
let user = User { id, name: input.name };
users.insert(id, user.clone());
Ok((axum::http::StatusCode::CREATED, Json(user)))
}
let state = AppState {
users: Arc::new(RwLock::new(HashMap::new())),
};
let app = Router::new()
.route("/health", get(health))
.route("/users/{id}", get(get_user))
.route("/users", post(create_user))
.with_state(state);
use axum::{http::StatusCode, response::{IntoResponse, Response}, Json};
use serde_json::json;
#[derive(Debug, thiserror::Error)]
pub enum AppError {
#[error("not found")]
NotFound,
#[error("invalid input: {0}")]
Validation(String),
}
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, message) = match &self {
AppError::NotFound => (StatusCode::NOT_FOUND, "not found".to_string()),
AppError::Validation(message) => (StatusCode::UNPROCESSABLE_ENTITY, message.clone()),
};
(status, Json(json!({ "error": message }))).into_response()
}
}
use std::time::Duration;
use axum::extract::DefaultBodyLimit;
use tower_http::{timeout::TimeoutLayer, trace::TraceLayer};
let app = Router::new()
.route("/health", get(health))
.route("/users/{id}", get(get_user))
.layer(DefaultBodyLimit::max(256 * 1024))
.layer(TimeoutLayer::new(Duration::from_secs(10)))
.layer(TraceLayer::new_for_http())
.with_state(state);
tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.init();
#[tokio::main]
async fn main() -> anyhow::Result<()> {
tracing_subscriber::fmt()
.with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
.init();
let state = AppState {
users: Arc::new(RwLock::new(HashMap::new())),
};
let app = build_app(state);
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await?;
axum::serve(listener, app)
.with_graceful_shutdown(async {
tokio::signal::ctrl_c().await.ok();
})
.await?;
Ok(())
}
use axum::{body::Body, http::{Request, StatusCode}};
use http_body_util::BodyExt;
use tower::ServiceExt;
#[tokio::test]
async fn health_returns_ok() {
let response = app()
.oneshot(Request::builder().uri("/health").body(Body::empty()).unwrap())
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = response.into_body().collect().await.unwrap().to_bytes();
assert_eq!(&body[..], b"OK");
}