入门指南

入门指南

让我们编写第一个actix-web应用程序!

Hello, world!

首先创建一个新的基于二进制的Cargo项目,然后切换到新目录:

cargo new hello-world
cd hello-world

现在,通过确保Cargo.toml包含以下内容,将actix-web添加为项目的依赖项:

[dependencies]
actix-web = "2.0"

如果要使用#[actix_rt::main]宏,则必须将actix-rt添加到依赖项中。 现在,您的Cargo.toml应该如下所示:

[dependencies]
actix-web = "2.0"
actix-rt = "1.0"

为了实现Web服务器,我们首先需要创建一个请求处理程序。 请求处理程序是一个异步函数,它接受零个或多个可以从请求中提取的参数(即impl FromRequest),并返回可以转换为HttpResponse的类型(即impl Responder):

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

async fn index() -> impl Responder {
    HttpResponse::Ok().body("Hello world!")
}

async fn index2() -> impl Responder {
    HttpResponse::Ok().body("Hello world again!")
}

接下来,创建一个App实例,使用_path_和特定的_HTTP方法_向应用程序的路由注册请求处理程序。 之后,该应用程序实例可以与HttpServer一起使用以监听传入的连接。 服务器接受应返回给应用程序的factory函数。

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

现在,使用cargo run编译并运行程序。 然后打开http://localhost:8088/查看结果。

注意:您可能会注意到#[actix_rt::main]属性宏。 该宏在actix运行时中执行标记的async函数。 任何async函数都可以通过此宏进行标记和执行。

使用属性宏定义路由

另外,您可以使用宏属性定义路由,这些宏属性允许您在函数上方指定路由,如下所示:

use actix_web::get;

#[get("/hello")]
async fn index3() -> impl Responder {
    HttpResponse::Ok().body("Hey there!")
}

然后,您可以使用service()注册route:

App::new()
    .service(index3)

出于一致性原因,本文档仅使用本页开头所示的显式语法。 但是,如果您更喜欢这种语法,那么在声明路由时就可以随意使用它,因为它只是语法糖。

要了解更多信息,请查看actix-web-codegen

热更新

如果需要,您可以在开发期间拥有一个自动重新加载(热更新)服务器,该服务器可以按需重新编译。 这不是必需的,但是它使得快速开发更加方便,因为您可以在保存后立即看到更改。 要了解如何完成此操作,请查看autoreload pattern

接下来: 应用