第3章 基础路由与处理器
好,现在我们已经把 Actix Web 的环境搭起来了。但说句实话,光有个能跑的服务器没什么意思——真正干活的是路由与处理器。这一节咱们就把这块核心内容吃透。
一、路由的基本概念
路由,说白了就是一套「请求分发规则」。客户端带着方法和路径来找你,你得知道该把这件事交给哪个函数去处理。这个「路径 → 函数」的映射关系,就是路由。
我在项目中见过不少新手把路由写得一团乱麻——所有接口堆在一个文件里,路径随意命名,参数到处乱放。后来我们团队定了一条规矩:路由就是 API 的地图,必须清晰、可预测。
一个最小可运行的路由示例
use actix_web::{web, App, HttpServer, Responder};
// 使用宏定义路由
#[get("/")]
async fn index() -> impl Responder {
"Hello, Actix!"
}
// 使用宏定义带路径参数的路由
#[get("/user/{id}")]
async fn get_user(path: web::Path<u32>) -> impl Responder {
format!("查询用户 ID: {}", path.into_inner())
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(index) // 注册宏定义的路由
.service(get_user)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
这段代码你应该能直接跑通。先注意两点:#[get("/")] 是宏,它帮我们自动实现了路由到处理器的映射;App::new().service(...) 则是把路由「挂载」到应用上。
#[get]、#[post])本质上是语法糖,编译时会展开成手写路由的代码。所以性能上没有任何损失,放心用。
二、GET 与 POST 路由
HTTP 方法决定了你能做什么操作。GET 通常用于查询资源,POST 用于创建资源。在 Actix 里,定义方式非常直白:
#[get("/path")]—— 处理 GET 请求#[post("/path")]—— 处理 POST 请求- 如果同一个路径需要支持多种方法,需要分别定义不同函数
use actix_web::{post, get, web, HttpResponse};
#[derive(serde::Deserialize)]
struct NewUser {
name: String,
email: String,
}
#[post("/users")]
async fn create_user(body: web::Json<NewUser>) -> HttpResponse {
// 这里实际应该把 user 写入数据库
HttpResponse::Created().json(format!("创建用户: {}", body.name))
}
#[get("/users")]
async fn list_users() -> HttpResponse {
HttpResponse::Ok().body("返回所有用户")
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(create_user)
.service(list_users)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
你可能注意到了,我用 web::Json<NewUser> 来接收 JSON 请求体。Actix 会自动帮你做反序列化,非常顺手。
三、路径参数与查询字符串
路径参数:从 URL 中提取变量
路径参数是 RESTful API 里最常用的设计方式。比如 /user/123 里的 123 就是路径参数。
use actix_web::{web, HttpResponse};
#[get("/user/{id}")]
async fn get_user(path: web::Path<u32>) -> HttpResponse {
let user_id = path.into_inner();
HttpResponse::Ok().body(format!("用户 ID: {}", user_id))
}
// 多参数示例
#[get("/order/{order_id}/item/{item_id}")]
async fn get_order_item(path: web::Path<(u32, u32)>) -> HttpResponse {
let (order_id, item_id) = path.into_inner();
HttpResponse::Ok().body(format!("订单 {},商品 {}", order_id, item_id))
}
有一点比较重要:路径参数的类型必须与访问路径匹配。比如 {id:u32} 只能匹配数字,如果传入非数字,Actix 会直接返回 400 错误,连我们的函数都不调用——这个特性我在生产环境里帮过大忙,少写了不少校验代码。
查询字符串:从 ? 后面提取参数
查询字符串长这样:/search?keyword=rust&page=1。用 web::Query 来取:
use actix_web::{web, HttpResponse};
use serde::Deserialize;
#[derive(Deserialize)]
struct SearchParams {
keyword: String,
page: Option<u32>, // 可选参数,用 Option 包裹
per_page: Option<u32>,
}
#[get("/search")]
async fn search(query: web::Query<SearchParams>) -> HttpResponse {
let per_page = query.per_page.unwrap_or(20); // 默认每页 20 条
HttpResponse::Ok().body(format!(
"搜索关键词: {},页码: {:?},每页: {}",
query.keyword, query.page, per_page
))
}
keyword 字段,Actix 会返回 400 Bad Request。可选参数一定要用 Option<T> 包裹,这是常见坑点。我以前就犯过这种错误——少传一个参数,前端直接收到 500 错误,排查了半天才发现是反序列化失败。
四、手动 Router 配置
宏虽然好用,但有些场景需要手动配置路由。比如你希望把一组路由挂在同一个路径前缀下,或者需要动态注册路由。这时候就该上 web::scope 了。
use actix_web::{web, HttpResponse, App};
async fn health_check() -> HttpResponse {
HttpResponse::Ok().body("OK")
}
async fn create_item() -> HttpResponse {
HttpResponse::Created().body("创建成功")
}
async fn get_item(path: web::Path<u32>) -> HttpResponse {
HttpResponse::Ok().body(format!("获取商品: {}", path.into_inner()))
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
// 使用 scope 分组
.service(
web::scope("/api/v1")
.route("/health", web::get().to(health_check))
.route("/items", web::post().to(create_item))
.route("/items/{id}", web::get().to(get_item))
)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
这段代码里,我们通过 web::scope("/api/v1") 给所有接口加了一个统一前缀。以后访问就是 /api/v1/health、/api/v1/items。个人习惯上,我比较推荐在项目里都用 scope 来组织路由,这样代码结构更清晰,方便维护。
路由和处理器匹配规则
有时候你会遇到「路由冲突」的问题——多个路由都匹配同一个请求。Actix 遵循一个规则:按注册顺序匹配,第一个匹配到的生效。
App::new()
.route("/user/{id}", web::get().to(get_user_by_id))
.route("/user/new", web::get().to(new_user)) // 这段永远不会被触发!
因为 /user/new 也会匹配 /user/{id},且先注册。所以:
原则:把静态路径放在动态路径前面,或者干脆把不同业务拆成不同的 scope。
五、路由配置综合示例
下面把今天的内容串起来,做一个「待办事项 API」:
use actix_web::{web, App, HttpServer, HttpResponse};
use serde::Deserialize;
#[derive(Deserialize)]
struct TodoItem {
title: String,
completed: bool,
}
#[derive(Deserialize)]
struct Pagination {
page: Option<u32>,
per_page: Option<u32>,
}
async fn list_todos(query: web::Query<Pagination>) -> HttpResponse {
let page = query.page.unwrap_or(1);
let per_page = query.per_page.unwrap_or(10);
HttpResponse::Ok().body(format!("列出待办,第 {} 页,每页 {} 条", page, per_page))
}
async fn create_todo(body: web::Json<TodoItem>) -> HttpResponse {
HttpResponse::Created().json(format!("创建: {}", body.title))
}
async fn get_todo(path: web::Path<u32>) -> HttpResponse {
HttpResponse::Ok().body(format!("查看待办 #{}", path.into_inner()))
}
async fn delete_todo(path: web::Path<u32>) -> HttpResponse {
HttpResponse::Ok().body(format!("删除待办 #{}", path.into_inner()))
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new()
.service(
web::scope("/todos")
.route("", web::get().to(list_todos))
.route("", web::post().to(create_todo))
.route("/{id}", web::get().to(get_todo))
.route("/{id}", web::delete().to(delete_todo))
)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
注意我这里 scope("/todos") 下,空字符串 "" 就代表 /todos 本身。web::delete() 是 Actix 提供的便捷方法之一,其他还有 web::put()、web::patch() 等。
scope 里再嵌套一层版本号,比如 web::scope("/api/v1").service(web::scope("/todos"))。这样后续升级 v2 时,老接口完全不受影响。
六、路由与处理器知识结构图
这张图把路由的两种配置方式、核心参数类型以及使用场景都列了出来。宏方式写起来快,适合小型项目和原型;手动 Router 配置灵活,适合中大型项目做统一管理。两种方式可以混合使用,没有硬性限制。
最后想多说一句——我们在实际项目中,80% 的接口都是简单的 CRUD,路由本身并不复杂。真正让你头疼的往往是「路由语义不清」导致的团队协作问题。所以命名规范、参数校验、错误处理,这些事情从一开始就做好,后面会省心很多。