Axum - Hello World:从这里开始学习 Axum
下面这个是 axum 库官方的示例 hello-world,运行之后,在浏览器里面打开 http://127.0.0.1:3000 就可以访问页面,页面会以 html 格式返回内容,页面中只有一个 <h1>Hello, World!</h1>。
//! Run with
//!
//! ```not_rust
//! cargo run -p example-hello-world
//! ```
use axum::{response::Html, routing::get, Router};
#[tokio::main]
async fn main() {
// build our application with a route
let app = Router::new().route("/", get(handler));
// run it
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
println!("listening on {}", listener.local_addr().unwrap());
axum::serve(listener, app).await;
}
async fn handler() -> Html<&'static str> {
Html("<h1>Hello, World!</h1>")
}涿部分拆解如下:
Router::new() 创建一个空的路由器
.route( 添加一条路由规则
"/", 路径:根路径
get(handler) GET 方法 + 处理函数 handler
)翻译成人话:当有人 GET 请求 / 时,调用 handler 函数处理。
多路由组合
有了这个开始之后,我们自己再来一个多路由组合:
use axum::{Router, routing::get, routing::post, Json};
use serde::{Deserialize, Serialize};
// ---------- 多个处理函数 ----------
async fn index() -> &'static str {
"首页"
}
async fn about() -> &'static str {
"关于页面"
}
async fn get_users() -> Json<Vec<String>> {
Json(vec!["Alice".into(), "Bob".into()])
}
async fn create_user() -> &'static str {
"创建用户"
}
async fn user_profile(id: axum::extract::Path<u32>) -> String {
format!("用户 {} 的个人主页", id.0)
}
#[tokio::main]
async fn main() {
let app = Router::new()
// GET 请求
.route("/", get(index))
.route("/about", get(about))
// 不同 HTTP 方法,同一路径
.route("/users", get(get_users)) // GET /users → 获取用户列表
.route("/users", post(create_user)) // POST /users → 创建用户
// 路径参数
.route("/users/:id", get(user_profile)) // /users/42 → "用户 42 的个人主页"
// 也可以链式写在同一路径上
.route("/api/data", get(get_data).post(post_data).delete(delete_data));
let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")
.await
.unwrap();
axum::serve(listener, app).await.unwrap();
}
## Router 常用的方法
let app = Router::new()
// .route() — 添加路由
.route("/", get(handler))
.route("/users", get(list_users).post(create_user))
// .merge() — 合并另一个 Router(模块化)
.merge(user_routes())
.merge(admin_routes())
// .nest() — 嵌套路由(带公共前缀)
.nest("/api", api_router()) // /api/users, /api/posts...
// .with_state() — 附加共享状态
.with_state(app_state)
// .fallback() — 404 处理
.fallback(not_found_handler)
// .layer() — 添加中间件
.layer(tower_http::cors::CorsLayer::permissive());