Rust强大的actor系统和最有趣的Web框架

安装

类型安全

忘记字符串类型的对象,从请求到响应,一切都有类型

功能丰富

Actix提供了许多现成的功能。 HTTP/2,日志记录等

可扩展的

轻松创建任何Actix应用程序都可以使用的自己的库。

快如闪电

Actix的速度非常快。不要相信我们的话--自己看看吧!

use actix_web::{web, App, HttpRequest, HttpServer, Responder};

async fn greet(req: HttpRequest) -> impl Responder {
    let name = req.match_info().get("name").unwrap_or("World");
    format!("Hello {}!", &name)
}

#[actix_rt::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .route("/", web::get().to(greet))
            .route("/{name}", web::get().to(greet))
    })
    .bind("127.0.0.1:8000")?
    .run()
    .await
}

灵活的响应

actix中的处理函数可以返回实现Responder特征的各种对象。从API返回一致的响应变得轻而易举。

#[derive(Serialize)]
struct Measurement {
    temperature: f32,
}

async fn hello_world() -> impl Responder {
    "Hello World!"
}

async fn current_temperature() -> impl Responder {
    web::Json(Measurement { temperature: 42.3 })
}

强大的提取器

Actix带有功能强大的提取器系统,该系统可从传入的HTTP请求中提取数据并将其传递给您的视图函数。 这不仅使API更加方便,而且还意味着您的视图函数可以是同步代码,并且仍然可以从异步IO处理中受益。

#[derive(Deserialize, Serialize)]
struct Event {
    id: Option<i32>,
    timestamp: f64,
    kind: String,
    tags: Vec<String>,
}

async fn capture_event(evt: web::Json<Event>) -> impl Responder {
    let new_event = store_in_db(evt.timestamp, &evt.kind, &evt.tags);
    format!("got event {}", new_event.id.unwrap())
}

简易表单处理

处理multipart/urlencoded的表单数据很容易。只需定义一个可以反序列化的结构,actix将处理其余的结构。

#[derive(Deserialize)]
struct Register {
    username: String,
    country: String,
}

async fn register(form: web::Form<Register>) -> impl Responder {
    format!("Hello {} from {}!", form.username, form.country)
}

请求路由

actix应用程序带有URL路由系统,可让您在URL上进行匹配并调用各个处理程序。为了获得更大的灵活性,可以使用scopes(范围)。

async fn index(_req: HttpRequest) -> impl Responder {
    "Hello from the index page!"
}

async fn hello(path: web::Path<String>) -> impl Responder {
    format!("Hello {}!", &path)
}

let app = App::new()
        .route("/", web::get().to(index))
        .route("/{name}", web::get().to(hello));