Rust Actix Web 入门指南
作者:Joshua Mo
日期:2023年12月15日
概述
- Actix Web 入门
- Actix Web 路由
- 添加数据库
- Actix Web 应用状态
- 中间件
- 静态文件服务
- 部署
- 总结
时至今日,Actix Web 仍然是 Rust Web 后端生态系统中极其强大的竞争者。尽管经历了一些事件,它依然保持强劲,成为 Rust 中最受推荐的 Web 框架之一。最初基于同名的 actor 框架(actix),现在已经脱离了原来的设计,现在 actix 主要用于 WebSocket 端点。
本文主要讨论 v4.4 版本。
Actix Web 入门
首先,使用 cargo init example-api
生成项目,然后进入项目目录,使用以下命令添加 actix-web 依赖:
cargo add actix-web
以下是基础的样板代码:
use actix_web::{
web, App, HttpServer, Responder};
#[get("/")]
async fn index() -> impl Responder {
"Hello world!"
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| {
App::new().service(
web::scope("/")
.route("/", web::get().to(index)),
)
})
.bind(("127.0.0.1", 8080))?
.run()
.await
}
Actix Web 路由
在 Actix Web 中,任何返回 actix_web::Responder
特征的函数都可以作为路由。下面是一个基本的 Hello World 示例:
#[get("/")]
async fn index() -> impl Responder {
"Hello world!"
}
对于更复杂的路由配置,可以使用 ServiceConfig
:
use actix_web::{
web, App, HttpResponse};
fn config(cfg