路由基础 #
路由是Web框架的核心功能,它决定了如何将HTTP请求映射到处理函数。Rocket使用属性宏来定义路由,使代码清晰易读。
什么是路由? #
路由是将URL路径和HTTP方法映射到处理函数的机制。当用户访问某个URL时,框架会根据路由规则找到对应的处理函数来处理请求。
text
HTTP请求 → 路由匹配 → 处理函数 → 响应
路由定义 #
基本语法 #
Rocket使用属性宏来定义路由:
rust
#[get("/path")]
fn handler() -> &'static str {
"Response"
}
HTTP方法 #
Rocket支持所有标准HTTP方法:
rust
#[get("/resource")]
fn get_resource() -> &'static str {
"GET: Read resource"
}
#[post("/resource")]
fn create_resource() -> &'static str {
"POST: Create resource"
}
#[put("/resource")]
fn update_resource() -> &'static str {
"PUT: Update resource"
}
#[patch("/resource")]
fn patch_resource() -> &'static str {
"PATCH: Partial update"
}
#[delete("/resource")]
fn delete_resource() -> &'static str {
"DELETE: Delete resource"
}
#[head("/resource")]
fn head_resource() -> &'static str {
"HEAD: Get headers only"
}
#[options("/resource")]
fn options_resource() -> &'static str {
"OPTIONS: Get allowed methods"
}
| 方法 | 用途 | 是否幂等 |
|---|---|---|
| GET | 获取资源 | 是 |
| POST | 创建资源 | 否 |
| PUT | 更新/替换资源 | 是 |
| PATCH | 部分更新 | 否 |
| DELETE | 删除资源 | 是 |
| HEAD | 获取响应头 | 是 |
| OPTIONS | 获取支持的方法 | 是 |
路由挂载 #
单个路由挂载 #
rust
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![index])
}
多个路由挂载 #
rust
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![
index,
get_resource,
create_resource,
update_resource,
delete_resource
])
}
多个挂载点 #
rust
#[launch]
fn rocket() -> _ {
rocket::build()
.mount("/", routes![index, about])
.mount("/api/users", routes![get_users, create_user])
.mount("/api/posts", routes![get_posts, create_post])
}
路由优先级 #
当多个路由匹配同一请求时,Rocket按以下规则确定优先级:
- 静态路径优先于动态路径
- 更具体的路径优先
- 声明顺序影响相同优先级的路由
rust
#[get("/users/new")]
fn new_user() -> &'static str {
"New user form"
}
#[get("/users/<id>")]
fn get_user(id: &str) -> String {
format!("User: {}", id)
}
访问 /users/new 会匹配 new_user,而不是 get_user。
路由重定向 #
永久重定向 #
rust
use rocket::response::Redirect;
#[get("/old-path")]
fn old_path() -> Redirect {
Redirect::permanent("/new-path")
}
#[get("/new-path")]
fn new_path() -> &'static str {
"New location"
}
临时重定向 #
rust
#[get("/temp")]
fn temp_redirect() -> Redirect {
Redirect::to("/target")
}
路由组 #
使用模块组织相关路由:
rust
mod api {
mod users {
#[get("/")]
pub fn list() -> &'static str {
"List users"
}
#[get("/<id>")]
pub fn get(id: u32) -> String {
format!("User {}", id)
}
}
mod posts {
#[get("/")]
pub fn list() -> &'static str {
"List posts"
}
}
}
#[launch]
fn rocket() -> _ {
rocket::build()
.mount("/api/users", routes![api::users::list, api::users::get])
.mount("/api/posts", routes![api::posts::list])
}
路由元数据 #
获取请求信息 #
rust
use rocket::http::{Method, ContentType};
use rocket::request::Request;
#[get("/info")]
fn info(request: &Request) -> String {
format!(
"Method: {}\nPath: {}\nContent-Type: {:?}",
request.method(),
request.uri().path(),
request.content_type()
)
}
条件路由 #
使用 rank 属性设置路由优先级:
rust
#[get("/user/<id>", rank = 2)]
fn user_by_id(id: u32) -> String {
format!("User by ID: {}", id)
}
#[get("/user/<name>", rank = 1)]
fn user_by_name(name: &str) -> String {
format!("User by name: {}", name)
}
路由匹配规则 #
精确匹配 #
rust
#[get("/exact/path")]
fn exact_match() -> &'static str {
"Exact match"
}
尾部斜杠 #
Rocket默认不区分尾部斜杠:
rust
#[get("/path")]
fn path() -> &'static str {
"Matches /path and /path/"
}
索引路由 #
rust
#[get("/")]
fn index() -> &'static str {
"Index page"
}
#[get("/users/")]
fn users_index() -> &'static str {
"Users index"
}
路由调试 #
查看所有路由 #
启动时Rocket会打印所有注册的路由:
text
🛰 Routes:
>> (index) GET /
>> (get_users) GET /api/users
>> (create_user) POST /api/users
路由冲突检测 #
Rocket会在编译时检测路由冲突:
rust
#[get("/same")]
fn route1() -> &'static str { "Route 1" }
#[get("/same")]
fn route2() -> &'static str { "Route 2" }
这会导致编译错误。
完整示例 #
rust
#[macro_use] extern crate rocket;
use rocket::response::Redirect;
#[get("/")]
fn index() -> &'static str {
"Welcome to the API"
}
#[get("/about")]
fn about() -> &'static str {
"About page"
}
#[get("/users")]
fn list_users() -> &'static str {
"List of users"
}
#[get("/users/<id>")]
fn get_user(id: u32) -> String {
format!("User ID: {}", id)
}
#[post("/users")]
fn create_user() -> &'static str {
"Create user"
}
#[put("/users/<id>")]
fn update_user(id: u32) -> String {
format!("Update user {}", id)
}
#[delete("/users/<id>")]
fn delete_user(id: u32) -> String {
format!("Delete user {}", id)
}
#[get("/old-users")]
fn old_users() -> Redirect {
Redirect::permanent("/users")
}
#[launch]
fn rocket() -> _ {
rocket::build()
.mount("/", routes![index, about])
.mount("/api", routes![
list_users,
get_user,
create_user,
update_user,
delete_user,
old_users
])
}
下一步 #
了解了路由基础后,让我们深入学习 路由属性,掌握更多路由定义的高级用法。
最后更新:2026-03-28