开始

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

Hello, world!

首先创建一个新的基于二进制的Cargo项目并进入新目录:

  1. cargo new hello-world
  2. cd hello-world

现在,确保actix-web的Cargo.toml 包含以下项目依赖关系:

  1. [dependencies]
  2. actix-web = "0.7"

为了实现一个Web服务器,我们首先需要创建一个请求处理程序。请求处理函数接受一个HttpRequest实例作为其唯一参数,并返回一个可转换为HttpResponse的类型:

文件名: src/main.rs

  1. extern crate actix_web;
  2. use actix_web::{server, App, HttpRequest};
  3. fn index(_req: &HttpRequest) -> &'static str {
  4. "Hello world!"
  5. }

接下来,创建一个Application实例,并将请求处理程序与应用程序的resource一起注册在特定HTTP方法和路径,然后,应用程序实例可以用于HttpServer来侦听将传入的连接。服务器接受一个应该返回一个HttpHandler实例的函数 。简单来说server::new可以使用了,它是HttpServer::new的简写:

  1. fn main() {
  2. server::new(|| App::new().resource("/", |r| r.f(index)))
  3. .bind("127.0.0.1:8088")
  4. .unwrap()
  5. .run();
  6. }

仅此而已!现在编译并运行该程序cargo run。去http://localhost:8088 看结果。

如果你想要在开发过程中重新编译后自动重新加载服务器。请查看自动重新加载模式