Actix 实战快速入门 Rust
1.hello world
这是 Actix Web 的 helloworld 示例。
rust
use actix_web::{get, web, App, HttpServer, Responder};
#[get("/")]
async fn index() -> impl Responder {
"Hello, World!"
}
#[get("/{name}")]
async fn hello(name: web::Path<String>) -> impl Responder {
format!("Hello {}!", &name)
}
#[actix_web::main]
async fn main() -> std::io::Result<()> {
HttpServer::new(|| App::new().service(index).service(hello))
.bind(("127.0.0.1", 8080))?
.run()
.await
}以下是为代码添加的详细中文注释说明,帮助理解 Rust 语法和 Actix-web 框架的运作方式(遇到不会的语法请直接去学习相应部分):
rust
// 导入actix-web框架所需的核心模块和宏
// web模块包含请求处理相关功能,App和HttpServer用于构建服务器,Responder用于响应生成
use actix_web::{get, web, App, HttpServer, Responder};
// 定义处理根路径/的路由
// #[get("/")] 是一个过程宏(proc macro),用于将函数标记为GET请求处理器
// async 关键字表示这是一个异步函数,Actix-web基于异步处理实现高性能
// -> impl Responder 表示返回一个实现了Responder trait的类型,该trait负责将返回值转换为HTTP响应
#[get("/")]
async fn index() -> impl Responder {
// 直接返回字符串,Rust会自动推导为&str类型,它实现了Responder trait
// 默认会生成200 OK状态码和text/plain内容类型
"Hello, World!"
}
// 定义处理动态路径的路由(例如:/Alice)
// {name} 是路径参数,使用web::Path提取器来捕获
// 这里的<String>指定参数类型,Actix-web会自动尝试将路径参数转换为String类型
#[get("/{name}")]
async fn hello(name: web::Path<String>) -> impl Responder {
// format! 宏用于创建格式化字符串,类似其他语言的字符串插值
// &name 是借用路径参数的值,Rust要求显式处理所有权
format!("Hello {}!", &name)
}
// 主函数,使用actix_web的运行时
// #[actix_web::main] 属性宏会将普通main函数转换为异步main函数
// 返回类型是std::io::Result<()> 表示可能包含IO错误
#[actix_web::main]
async fn main() -> std::io::Result<()> {
// 创建HTTP服务器实例
HttpServer::new(|| {
// 闭包(匿名函数)每次被调用时创建新的App实例
// 这是Actix-web的线程模型要求,确保每个工作线程有自己的应用实例
App::new()
// 注册路由服务,将index和hello函数添加到应用路由表
.service(index)
.service(hello)
})
// 绑定服务器到本地地址和端口
.bind(("127.0.0.1", 8080))?
// 启动服务器并等待(异步)
.run()
// await关键字表示等待异步操作完成
// 这里会阻塞主线程直到服务器停止(例如通过Ctrl+C)
.await
}运作流程说明:
- 服务启动:当执行
cargo run时,main 函数被调用 - 服务器创建:
HttpServer::new()创建服务器实例,闭包参数用于创建 App 实例 - 路由注册:通过
.service()方法将路由处理函数添加到应用的路由表中 - 绑定端口:
.bind()指定监听的 IP 和端口(这里是本地 8080 端口) - 运行服务器:
.run()启动服务器,开始监听请求 - 请求处理流程:
- 当用户访问
http://localhost:8080/时,触发 index 函数 - 当访问
http://localhost:8080/John时,触发 hello 函数,路径参数"John"会被捕获 - Actix-web 自动将返回值转换为 HTTP 响应(包括设置合适的 Content-Type)
- 当用户访问
关键 Rust 语法说明:
宏系统:
#[get(...)]:属性宏,用于路由绑定format!:格式化字符串宏,编译时检查格式安全性
异步编程:
async/await:Rust 的异步语法,Actix-web 基于 tokio 运行时实现高性能异步 IO
所有权系统:
&name:使用引用(borrowing)避免所有权转移,符合 Rust 的内存安全原则
Trait 系统:
impl Responder:使用 trait 约束返回类型,允许灵活返回不同但兼容的类型
错误处理:
?操作符:自动传播错误,bind()可能返回的 IO 错误会被传递到 main 的返回值
2.阅读 Actix 的基础文档
仅 getting-started 部分。 基本理解即可,不必全部搞懂。 https://actix.rs/docs/getting-started
3.运行官方示例
shell
git clone https://github.com/actix/actix
cd actix
cargo run --example ping阅读示例代码,理解 Actix Web 的基本用法,可自行删删改改,加深理解。 不会的部分请查阅文档。