第一个应用 #
本节将带你创建第一个Rocket应用,从最简单的Hello World开始,逐步了解Rocket的核心概念。
最简单的Hello World #
创建一个最基础的Rocket应用只需要几行代码:
rust
#[macro_use] extern crate rocket;
#[get("/")]
fn index() -> &'static str {
"Hello, Rocket!"
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![index])
}
代码解析 #
| 部分 | 说明 |
|---|---|
#[macro_use] |
导入Rocket宏 |
#[get("/")] |
定义GET路由 |
fn index() |
路由处理函数 |
#[launch] |
启动Rocket应用 |
rocket::build() |
创建Rocket实例 |
.mount() |
挂载路由 |
routes![] |
路由列表宏 |
运行应用 #
bash
cargo run
输出:
text
🔧 Configured for debug.
>> address: 127.0.0.1
>> port: 8000
>> workers: 4
>> keep-alive: 5s
>> limits: bytes = 8KiB, data-form = 2MiB, file = 1MiB, json = 1MiB, msgpack = 1MiB, string = 8KiB
>> tls: disabled
>> shutdown: ctrlc = true, force = true, signals = [SIGTERM], grace = 2s, mercy = 3s
🛰 Routes:
>> (index) GET /
🚀 Rocket has launched from http://127.0.0.1:8000
访问 http://127.0.0.1:8000 即可看到 “Hello, Rocket!”。
添加更多路由 #
不同HTTP方法 #
rust
#[get("/")]
fn index() -> &'static str {
"GET: Index page"
}
#[post("/")]
fn create() -> &'static str {
"POST: Create resource"
}
#[put("/")]
fn update() -> &'static str {
"PUT: Update resource"
}
#[delete("/")]
fn delete() -> &'static str {
"DELETE: Delete resource"
}
#[launch]
fn rocket() -> _ {
rocket::build().mount("/", routes![index, create, update, delete])
}
路由挂载点 #
rust
#[get("/")]
fn api_index() -> &'static str {
"API Index"
}
#[get("/users")]
fn api_users() -> &'static str {
"API Users"
}
#[launch]
fn rocket() -> _ {
rocket::build()
.mount("/", routes![index])
.mount("/api", routes![api_index, api_users])
}
访问路径:
/→ index/api→ api_index/api/users→ api_users
动态路由参数 #
单个参数 #
rust
#[get("/hello/<name>")]
fn hello(name: &str) -> String {
format!("Hello, {}!", name)
}
访问 /hello/Rocket 返回 “Hello, Rocket!”
多个参数 #
rust
#[get("/user/<id>/post/<post_id>")]
fn user_post(id: u32, post_id: u32) -> String {
format!("User {}'s post {}", id, post_id)
}
参数类型 #
Rocket支持多种参数类型:
rust
#[get("/int/<num>")]
fn int_param(num: i32) -> String {
format!("Integer: {}", num)
}
#[get("/float/<num>")]
fn float_param(num: f64) -> String {
format!("Float: {}", num)
}
#[get("/path/<path..>")]
fn path_param(path: std::path::PathBuf) -> String {
format!("Path: {:?}", path)
}
#[get("/optional/<name>")]
fn optional_param(name: Option<&str>) -> String {
match name {
Some(n) => format!("Hello, {}!", n),
None => "Hello, stranger!".to_string(),
}
}
| 类型 | 说明 | 示例URL |
|---|---|---|
&str |
字符串切片 | /hello/world |
String |
拥有所有权的字符串 | /hello/world |
i32, u32 |
整数类型 | /user/123 |
f64 |
浮点数 | /price/99.99 |
PathBuf |
路径(多段) | /files/a/b/c |
Option<T> |
可选参数 | /greet/Some(name) |
查询参数 #
rust
use rocket::request::Query;
#[derive(rocket::FromForm)]
struct SearchQuery {
q: String,
page: Option<usize>,
}
#[get("/search?<query..>")]
fn search(query: Query<SearchQuery>) -> String {
let page = query.page.unwrap_or(1);
format!("Searching '{}' on page {}", query.q, page)
}
访问 /search?q=rocket&page=2 返回 “Searching ‘rocket’ on page 2”
返回JSON响应 #
添加依赖 #
toml
[dependencies]
rocket = { version = "0.5", features = ["json"] }
serde = { version = "1.0", features = ["derive"] }
定义JSON响应 #
rust
use rocket::serde::json::Json;
use rocket::serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize)]
#[serde(crate = "rocket::serde")]
struct User {
id: u32,
name: String,
email: String,
}
#[get("/user/<id>")]
fn get_user(id: u32) -> Json<User> {
Json(User {
id,
name: "Alice".to_string(),
email: "alice@example.com".to_string(),
})
}
#[post("/user", format = "json", data = "<user>")]
fn create_user(user: Json<User>) -> Json<User> {
user
}
错误处理 #
返回Result #
rust
use rocket::http::Status;
#[get("/user/<id>")]
fn get_user(id: u32) -> Result<Json<User>, Status> {
if id == 0 {
Err(Status::NotFound)
} else {
Ok(Json(User {
id,
name: "Alice".to_string(),
email: "alice@example.com".to_string(),
}))
}
}
自定义错误响应 #
rust
use rocket::response::content::RawHtml;
#[catch(404)]
fn not_found() -> RawHtml<&'static str> {
RawHtml("<h1>404 - Page Not Found</h1>")
}
#[launch]
fn rocket() -> _ {
rocket::build()
.mount("/", routes![index])
.register("/", catchers![not_found])
}
完整示例 #
rust
#[macro_use] extern crate rocket;
use rocket::serde::json::Json;
use rocket::serde::{Deserialize, Serialize};
use rocket::http::Status;
use rocket::response::content::RawHtml;
#[derive(Serialize, Deserialize)]
#[serde(crate = "rocket::serde")]
struct User {
id: u32,
name: String,
email: String,
}
#[get("/")]
fn index() -> RawHtml<&'static str> {
RawHtml("<h1>Welcome to Rocket!</h1>")
}
#[get("/hello/<name>")]
fn hello(name: &str) -> String {
format!("Hello, {}!", name)
}
#[get("/user/<id>")]
fn get_user(id: u32) -> Result<Json<User>, Status> {
if id == 0 {
Err(Status::NotFound)
} else {
Ok(Json(User {
id,
name: "Alice".to_string(),
email: "alice@example.com".to_string(),
}))
}
}
#[post("/user", format = "json", data = "<user>")]
fn create_user(user: Json<User>) -> Json<User> {
println!("Creating user: {:?}", user);
user
}
#[catch(404)]
fn not_found() -> RawHtml<&'static str> {
RawHtml("<h1>404 - Page Not Found</h1>")
}
#[catch(500)]
fn internal_error() -> RawHtml<&'static str> {
RawHtml("<h1>500 - Internal Server Error</h1>")
}
#[launch]
fn rocket() -> _ {
rocket::build()
.mount("/", routes![index, hello, get_user, create_user])
.register("/", catchers![not_found, internal_error])
}
测试API #
使用curl测试:
bash
# GET请求
curl http://127.0.0.1:8000/
curl http://127.0.0.1:8000/hello/Rocket
curl http://127.0.0.1:8000/user/1
# POST请求
curl -X POST http://127.0.0.1:8000/user \
-H "Content-Type: application/json" \
-d '{"id":1,"name":"Bob","email":"bob@example.com"}'
下一步 #
现在你已经创建了第一个Rocket应用,接下来让我们了解 项目结构,学习如何组织更大型的Rocket项目。
最后更新:2026-03-28