Rust 用 Actix Web 构建 REST API:路由、应用状态与错误处理
test12026-10-063 次阅读
Actix Web 与 Axum 的不同取向
Axum 偏重 tower 生态与 trait 组合,Actix Web 用宏与 actor 风格的 App 配置,上手更直白。两者都能写生产级 API,这里以 Actix Web 演示一条最小可用的用户接口。
定义路由与处理器
use actix_web::{get, post, web, App, HttpResponse, HttpServer};
#[get("/users/{id}")]
async fn get_user(path: web::Path<i64>) -> HttpResponse {
let id = path.into_inner();
HttpResponse::Ok().json(serde_json::json!({ "id": id, "name": "demo" }))
}
#[post("/users")]
async fn create_user(body: web::Json<serde_json::Value>) -> HttpResponse {
HttpResponse::Created().json(body.into_inner())
}
共享应用状态
用 web::Data 把连接池等状态注入处理器,Actix 会按 Arc 包裹并保证跨请求安全共享。
struct AppState {
env: String,
}
#[get("/health")]
async fn health(state: web::Data<AppState>) -> HttpResponse {
HttpResponse::Ok().body(format!("env={}", state.env))
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
let state = web::Data::new(AppState { env: "prod".into() });
HttpServer::new(move || {
App::new()
.app_data(state.clone())
.service(get_user)
.service(create_user)
.service(health)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
统一错误返回
实现 ResponseError 让业务错误直接作为响应返回,避免在每个处理器里手写状态码。
use actix_web::{HttpResponse, ResponseError};
#[derive(Debug)]
struct NotFound;
impl ResponseError for NotFound {
fn error_response(&self) -> HttpResponse {
HttpResponse::NotFound().json(serde_json::json!({ "error": "not_found" }))
}
}
落地建议
- 路由多时用 configure 拆分模块,保持 main 清爽。
- 入参校验用 serde + validator,出参统一包一层 ApiResponse 结构。
- 跨处理器共享的状态必须 Send + Sync,数据库池、HTTP 客户端都满足。
T
test1
文章作者
Actix Web 与 Axum 的不同取向 Axum 偏重 tower 生态与 trait 组合,Actix Web...
- 分类
- 技术
- 发布时间
- 2026-10-06
- 字数
- 约 1628 字
- 阅读
- 3 次
