tokio-rs/axum
GitHub: tokio-rs/axum
axum 是一个基于 Rust 和 hyper 的异步 HTTP Web 框架,通过无宏 API、提取器模式和 tower 生态集成,提供高人体工程学、模块化的路由与请求处理能力。
Stars: 26685 | Forks: 1453
# axum
`axum` 是一个专注于人体工程学和模块化的 HTTP 路由和请求处理库。
[](https://github.com/tokio-rs/axum/actions/workflows/CI.yml)
[](https://crates.io/crates/axum)
[][docs]
关于该 crate 的更多信息可以在 [crate 文档][docs] 中找到。
## 核心功能
- 使用无宏 API 将请求路由到处理程序。
- 使用提取器声明式地解析请求。
- 简单且可预测的错误处理模型。
- 以最少的样板代码生成响应。
- 充分利用 [`tower`] 和 [`tower-http`] 生态系统中的
中间件、服务和实用工具。
特别是最后一点,使 `axum` 与其他库/框架区别开来。
`axum` 没有自己的中间件系统,而是使用
[`tower::Service`]。这意味着 `axum` 可以免费获得超时、追踪、压缩、
授权等功能。它还使您能够与
使用 [`hyper`] 或 [`tonic`] 编写的应用程序共享中间件。
## ⚠ 破坏性更改 ⚠
我们目前正在推进 axum 0.9 的开发,因此 `main` 分支包含破坏性
更改。有关发布到 crates.io 的版本,请参阅 [`0.8.x`] 分支。
## 使用示例
```
use axum::{
routing::{get, post},
http::StatusCode,
Json, Router,
};
use serde::{Deserialize, Serialize};
#[tokio::main]
async fn main() {
// initialize tracing
tracing_subscriber::fmt::init();
// build our application with a route
let app = Router::new()
// `GET /` goes to `root`
.route("/", get(root))
// `POST /users` goes to `create_user`
.route("/users", post(create_user));
// run our app with hyper, listening globally on port 3000
let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap();
axum::serve(listener, app).await;
}
// basic handler that responds with a static string
async fn root() -> &'static str {
"Hello, World!"
}
async fn create_user(
// this argument tells axum to parse the request body
// as JSON into a `CreateUser` type
Json(payload): Json,
) -> (StatusCode, Json) {
// insert your application logic here
let user = User {
id: 1337,
username: payload.username,
};
// this will be converted into a JSON response
// with a status code of `201 Created`
(StatusCode::CREATED, Json(user))
}
// the input to our `create_user` handler
#[derive(Deserialize)]
struct CreateUser {
username: String,
}
// the output to our `create_user` handler
#[derive(Serialize)]
struct User {
id: u64,
username: String,
}
```
您可以在[示例目录][examples]中找到此[示例][readme-example]以及其他示例项目。
请参阅 [crate 文档][docs] 以获取更多示例。
## 性能
`axum` 是位于 [`hyper`] 之上的一个相对较薄的层,只增加了非常少的
开销。因此,`axum` 的性能可与 [`hyper`] 相媲美。您可以
在[这里](https://github.com/programatik29/rust-web-benchmarks) 和
[这里](https://web-frameworks-benchmark.netlify.app/result?l=rust) 找到基准测试。
## 安全性
此 crate 使用 `#![forbid(unsafe_code)]` 来确保所有内容都使用
100% 安全的 Rust 实现。
## 最低支持的 Rust 版本
axum 的 MSRV 为 1.80。
## 示例
[examples] 文件夹包含如何使用 `axum` 的各种示例。
[docs] 也提供了大量的代码片段和示例。
## 获取帮助
在 `axum` 的仓库中,我们还提供了[一些示例][examples],展示了如何
将所有内容组合在一起。也欢迎您在 [Discord 频道][chat] 中提问,或者就您的问题发起一个 [讨论][discussion]。
## 许可证
本项目基于 [MIT 许可证][license] 授权。
### 贡献
除非您明确声明,否则由您有意提交以包含在 `axum` 中的任何贡献,
均应按 MIT 授权,无需任何
附加条款或条件。
标签:HTTP路由, Rust, Tower, Web框架, 中间件, 可视化界面, 网络流量审计, 通知系统