Axum Web 框架基础
学习目标
- 掌握 Axum 基本路由
- 理解 Handler 签名
- 掌握响应类型
核心概念
基本服务器
[dependencies]
axum = "0.7"
tokio = { version = "1", features = ["full"] }
use axum::{Router, routing::get};
async fn hello() -> &'static str {
"Hello, World!"
}
async fn health() -> &'static str {
"OK"
}
#[tokio::main]
async fn main() {
let app = Router::new()
.route("/", get(hello))
.route("/health", get(health));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
路径参数
use axum::{Router, routing::get, extract::Path};
async fn user_detail(Path(id): Path<u32>) -> String {
format!("用户 ID: {}", id)
}
async fn user_posts(Path((user_id, post_id)): Path<(u32, u32)>) -> String {
format!("用户 {} 的帖子 {}", user_id, post_id)
}
fn app() -> Router {
Router::new()
.route("/users/{id}", get(user_detail))
.route("/users/{user_id}/posts/{post_id}", get(user_posts))
}
Query 参数
use axum::{Router, routing::get, extract::Query};
use serde::Deserialize;
#[derive(Deserialize)]
struct Pagination {
page: Option<u32>,
limit: Option<u32>,
}
async fn list_items(Query(params): Query<Pagination>) -> String {
let page = params.page.unwrap_or(1);
let limit = params.limit.unwrap_or(10);
format!("page={}, limit={}", page, limit)
}
JSON 响应
use axum::{Router, routing::get, Json};
use serde::Serialize;
#[derive(Serialize)]
struct User {
id: u32,
name: String,
}
async fn get_user() -> Json<User> {
Json(User {
id: 1,
name: "Alice".to_string(),
})
}
POST 请求体
use axum::{Router, routing::post, Json};
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct CreateUser {
name: String,
email: String,
}
#[derive(Serialize)]
struct Response {
success: bool,
id: u32,
}
async fn create_user(Json(input): Json<CreateUser>) -> Json<Response> {
println!("创建用户: {} ({})", input.name, input.email);
Json(Response { success: true, id: 1 })
}
fn app() -> Router {
Router::new().route("/users", post(create_user))
}
小结
| 功能 | 语法 |
|---|
| 路由 | .route("/path", get(handler)) |
| 路径参数 | Path(id): Path<u32> |
| Query | Query(params): Query<T> |
| JSON 输入 | Json(body): Json<T> |
| JSON 输出 | Json(value) |