使用 Rust Axum 构建 Web API
wxk1991 Lv5

使用 Rust Axum 构建 Web API

Axum 是 Tokio 生态里的 Web 框架,设计简洁,和 Tower、Hyper 集成紧密。它适合构建高性能 API 服务,也适合学习 Rust 后端开发的基本模式。


一、添加依赖

1
2
3
4
[dependencies]
axum = "0.7"
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }

二、创建路由

1
2
3
4
5
6
7
8
9
10
11
12
use axum::{routing::get, Router};

async fn health() -> &'static str {
"ok"
}

#[tokio::main]
async fn main() {
let app = Router::new().route("/health", get(health));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await.unwrap();
}

访问:

1
curl http://localhost:3000/health

三、返回 JSON

1
2
3
4
5
6
7
8
9
10
11
12
use axum::Json;
use serde::Serialize;

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

async fn get_user() -> Json<User> {
Json(User { id: 1, name: "Alice".to_string() })
}

Axum 通过类型来表达响应,很符合 Rust 的风格。


四、共享状态

真实服务通常需要数据库连接池、配置、缓存客户端等共享状态:

1
2
3
4
#[derive(Clone)]
struct AppState {
app_name: String,
}

然后使用 Router::with_state 注入。


五、适用场景

Axum 适合对性能、稳定性和类型约束要求较高的 API。它的学习成本高于 Go 或 Node.js 框架,但换来的是更明确的错误边界和更少的运行时意外。

如果项目团队已经熟悉 Rust,Axum 是一个很值得考虑的后端选择。