Rust异步Web框架

介绍Rust异步Web框架生态

异步Web框架生态

Rocket框架

官方教程:The Rocket Programming Guide

Rocket设计核心哲学:

  • Security, correctness, and developer experience are paramount.
  • All request handling information should be typed and self-contained.
  • Decisions should not be forced.

Lifecycle

Rocket’s main task is to listen for incoming web requests, dispatch the request to the application code, and return a response to the client. We call the process that goes from request to response the “lifecycle”. We summarize the lifecycle as the following sequence of steps:

  1. Routing 路由
  2. Validation 验证
  3. Processing 处理
  4. Response 回复
1
2
3
4
#[get("/world")]              // <- route attribute
fn world() -> &'static str {  // <- request handler
    "hello, world!"
}

Lanuching

Rocket begins serving requests after being launched, which starts a multi-threaded asynchronous server and dispatches requests to matching routes as they arrive.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
#[macro_use] extern crate rocket;

#[get("/world")]
fn world() -> &'static str {
    "Hello, world!"
}

#[launch]
fn rocket() -> _ {
    rocket::build().mount("/hello", routes![world])
}

Dynamic Paths

1
2
3
4
#[get("/hello/<name>")]
fn hello(name: &str) -> String {
    format!("Hello, {}!", name)
}

Forwarding

Routes are attempted in increasing rank order. Rocket chooses a default ranking from -12 to -1, detailed in the next section, but a route’s rank can also be manually set with the rank attribute. To illustrate, consider the following routes:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
#[get("/user/<id>")]
fn user(id: usize) { /* ... */ }

#[get("/user/<id>", rank = 2)]
fn user_int(id: isize) { /* ... */ }

#[get("/user/<id>", rank = 3)]
fn user_str(id: &str) { /* ... */ }

#[launch]
fn rocket() -> _ {
    rocket::build().mount("/", routes![user, user_int, user_str])
}

actix-web

官方文档:actix_web

可以通过宏来创建提取器。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
use actix_web::{get, web, App, HttpServer, Responder};

#[get("/hello/{name}")]
async fn greet(name: web::Path<String>) -> impl Responder {
    format!("Hello {}!", name)
}

#[actix_web::main] // or #[tokio::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new().service(greet)
    })
    .bind(("127.0.0.1", 8080))?
    .run()
    .await
}

其他

actix-web底层基于actix-net中间库,封装了和网络相关的东西。

在actix-net/actix-rt/src/arbiter.rs下每个arbiter对应一个线程。

gotham

比较早的框架,基于tokio实现。

Thruster

构建于hyper之上,这个中间件在请求过程中设置上下文。

tower

文档: tower

Tower is a library of modular and reusable components for building robust networking clients and servers.

hyper

官方文档:hyper

关于路由用到route-recognizer,它的底层是非确定有限状态自动机

warp

github仓库地址:warp

filter的工作机制,基于hyper。Rust-Warp-Example是一个应用实例。

一些底层的库

  • http:解析处理HTTP协议,对http请求和响应做了一个类型抽象。
  • http-body:做异步http请求和响应。
  • http-types:基于async-std。
  • tower-http:基于tower、http、http-body、的中间件。
  • hyper:HTTP的实现,没有整合tower-http。

Rust异步Web框架

结构:

  • 框架接口设计
  • 路由结构实现
  • 实现Handler
  • 添加tracing打印日志
  • 实现提取器
  • 实现中间件
  • 错误处理

补充学习

课程回顾

参考资料

张汉东的Rust实战课

张汉东的Rust实战课视频课程代码示例