Full Code of dslchd/actix-web3-CN-doc for AI

master 003c04a4ebdd cached
48 files
114.9 KB
41.4k tokens
109 symbols
1 requests
Download .txt
Repository: dslchd/actix-web3-CN-doc
Branch: master
Commit: 003c04a4ebdd
Files: 48
Total size: 114.9 KB

Directory structure:
gitextract_y59kkk7e/

├── .gitignore
├── Cargo.toml
├── LICENSE
├── README.md
├── doc/
│   ├── Application.md
│   ├── AutoReloading.md
│   ├── ConnectionLifecycle.md
│   ├── Databases.md
│   ├── Errors.md
│   ├── Extractors.md
│   ├── GettingStarted.md
│   ├── HTTP2.md
│   ├── HTTPServerInitialization.md
│   ├── Handlers.md
│   ├── Middleware.md
│   ├── Requests.md
│   ├── Responses.md
│   ├── Server.md
│   ├── StaticFiles.md
│   ├── Testing.md
│   ├── URLDispatch.md
│   ├── Webscokets.md
│   ├── WelcomeToActix.md
│   └── WhatIsActix.md
└── src/
    ├── bin/
    │   ├── application.rs
    │   ├── errors_custom_error_response.rs
    │   ├── extractors_application_state_arc.rs
    │   ├── extractors_application_state_cell.rs
    │   ├── extractors_json.rs
    │   ├── extractors_type_safe_path.rs
    │   ├── handlers_different_return_types.rs
    │   ├── handlers_request_handlers.rs
    │   ├── handlers_response_with_custom_type.rs
    │   ├── handlers_streaming_response_body.rs
    │   ├── hello_world.rs
    │   ├── middleware.rs
    │   ├── middleware_error_handler.rs
    │   ├── middleware_logging.rs
    │   ├── middleware_session.rs
    │   ├── requests.rs
    │   ├── responses.rs
    │   ├── server.rs
    │   ├── server_graceful_shutdown.rs
    │   ├── server_keepalive.rs
    │   ├── static_file.rs
    │   ├── url_dispatch_scoping.rs
    │   └── websocket_echo.rs
    └── main.rs

================================================
FILE CONTENTS
================================================

================================================
FILE: .gitignore
================================================
/target
*.iml
.idea




================================================
FILE: Cargo.toml
================================================
[package]
name = "actix-web3-CN-doc"
version = "0.1.0"
authors = ["dslchd <dslchd@qq.com>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
# 添加actix-web 3.0版本依赖
#actix-web = { version = "3", features = ["openssl"] }
#openssl = { version = "0.10" }
actix-web = "3"
# 异步请求与响应操作的组合器
actix-service = "1.0.6"
actix-session = "0.4.0"
actix-files = "0.3.0"
actix-web-actors = "3.0.0"
actix = "0.10.0"
# 序列化
serde = "1.0.116"
serde_json = "1.0.57"
futures = "0.3.5"
env_logger = "0.7"
bytes = "0.5"
rand = "0.7.3"
derive_more = "0.99.10"
log = "0.4.11"

================================================
FILE: LICENSE
================================================
MIT License

Copyright (c) 2020 dslchd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


================================================
FILE: README.md
================================================
# actix-web 3.0 中文文档

## 1.说明
基本上算是翻译了官文档,但是示例并不一定和官方的相同. 所有的示例代码都源自官方文档中的示例,但又不完全与之相同.

算是一边学习一边理解写出来的demo代码且全部都能正常运行.

可以使用如下命令 + 指定文件名执行并查看结果:

```shell script
cargo run --bin hello_world
```

**另外:** `Actix-Web` 的网络部分是基于[Tokio](https://tokio.rs/tokio/tutorial) 来实现的. 因此要想更加深入的了解`Actix-web`的实现细节, `Tokio`是你
必须要学习和了解的框架. `Tokio` 的中文文档指南请参考: [这里](https://github.com/dslchd/tokio-cn-doc).

## 2.文档索引
### 介绍(Introduction)
[欢迎(Welcome)](doc/WelcomeToActix.md)

[什么是Actix(What is Actix)](doc/WhatIsActix.md)
### 基础(Basics)
[起步(Getting Started)](doc/GettingStarted.md)

[应用(Application)](doc/Application.md)

[服务器(Server)](doc/Server.md)

[处理器(Handlers)](doc/Handlers.md)

[提取器(Extractors)](doc/Extractors.md)

### 高级(Advanced)
[错误(Errors)](doc/Errors.md)

[URL分发(URL Dispatch)](doc/URLDispatch.md)

[请求(Requests)](doc/Requests.md)

[响应(Responses)](doc/Responses.md)

[测试(Testing)](doc/Testing.md)

[中间件(Middleware)](doc/Middleware.md)

[静态文件(Static Files)](doc/StaticFiles.md)

### 协议(Protocols)
[Websockets](doc/Webscokets.md)

[HTTP/2](doc/HTTP2.md)

## 模式(Patterns)
[自动重载(Auto-Reloading)](doc/AutoReloading.md)

[数据库(Databases)](doc/Databases.md)

## 图解(Diagrams)
[HTTP服务初始化(HTTP Server Initialization)](doc/HTTPServerInitialization.md)

[链接生命周期(Connection Lifecycle)](doc/ConnectionLifecycle.md)

## API文档
[actix](https://docs.rs/actix)

[actix-web](https://docs.rs/actix-web/)

## 3.其它
由于水平有限,在翻译过程中过程中难免有错误或遗漏,可以发现后及时向我提出(提 issue).

希望此文档能给不想看英文原文或英文不太好的朋友, 在使用或学习 `Actix-web` 与 `Rust` 来开发Web应用时带来帮助,
大家共同提高, 为Rust的流行作出丁点贡献.

**如果觉得给你的学习带来了帮助, 可以帮忙点个star, 这将是我一直同步更新下去的动力.**

================================================
FILE: doc/Application.md
================================================
## 编写一个应用程序(Writing an Application)
`actix-web` 里面提供了一系列可以使用rust来构建web server的原语。它提供了路由,中间件,request预处理,response的后置处理等。

所有的 `actix-web` 服务都围绕App实例来构建. 它被用来注册路由资源和中间件. 它也存储同一个scope内所有处理程序之间共享的应用程序状态.

应用的 `scope` 扮演所有路由命名空间的角色, 比如, 为所有的路由指定一个应用级范围(scope), 那么就会有一个相同前缀的url路径.
应用前缀总是包含一个 "/" 开头,如果提供的前缀没有包含斜杠,那么会默认自动的插入一个斜杠.

比如应用使用 `/app` 来限定, 那么任何使用了路径为 `/app`, `/app/` 或者 `/app/test` 的请求都将被匹配,但是` /application` 这种path不会被匹配.

```rust
use actix_web::{web, App, HttpServer, Responder};

async fn index() -> impl Responder {
    "Hello world!"
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new().service(
            // 所有资源与路由加上前缀...
            web::scope("/app")
                // ...因此handler的请求是对应 `GET /app/index.html`
                .route("/index.html", web::get().to(index)),
        )
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```

在此示例中,将创建具有 `/app` 前缀和 `index.html` 资源的应用程序.因此完整的资源路径url就是 `/app/index.html`.

更多的信息,将会在 `URL Dispatch` 章节讨论.

## 状态(State)
应用程序状态(State)被同一作用域(Scope)内的所有路由和资源共享.State 能被 `web::Data<T>` 来访问,其中 `T` 是 state的类型. State也能被中间件访问.

让我们编写一个简单的应用程序并将应用程序名称存储在状态中,你可以在应用程序中注册多个State.

```rust
use actix_web::{get, web, App, HttpServer};

// 这个结构体代表一个State
struct AppState {
    app_name: String,
}

#[get("/")]
async fn index(data: web::Data<AppState>) -> String {
    let app_name = &data.app_name; // <- 得到app名

    format!("Hello {}!", app_name) // <- 响应app名
}
```

并且在初始化 app 时传递状态(state),然后再启动应用程序:

```rust
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .data(AppState {
                app_name: String::from("Actix-web"),
            })
            .service(index)
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```
你可以在应用中注册任意数量的状态类型.

## 共享可变状态(Shared Mutable State)
`HttpServer` 接收一个应用程序工厂而不是一个应用程序实例, 一个 `HttpServer` 为每一个线程构造一个应用程序实例.
因此必须多次构造应用程序数据,如果你想在两个不同的线程之间共享数据,一个可以共享的对象可以使用比如: `Sync + Send`.

内部 `web::Data` 使用 `Arc`. 因此为了避免创建两个 `Arc`, 我们应该在在使用 `App::app_data()` 之前创建好我们的数据.

下面的例子中展示了应用中使用可变共享状态, 首先我们定义state并创建处理器(handler).

```rust
use actix_web::{web, App, HttpServer};
use std::sync::Mutex;

struct AppStateWithCounter {
    counter: Mutex<i32>, // <- Mutex 必须安全的在线程之间可变
}

async fn index(data: web::Data<AppStateWithCounter>) -> String {
    let mut counter = data.counter.lock().unwrap(); // <- 得到 counter's MutexGuard
    *counter += 1; // <- 在 MutexGuard 内访问 counter

    format!("Request number: {}", counter) // <- 响应counter值
}
```

并在 `App` 中注册数据:

```rust
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let counter = web::Data::new(AppStateWithCounter {
        counter: Mutex::new(0),
    });

    HttpServer::new(move || {
        // 移动 counter 进闭包中
        App::new()
            // 注意这里使用 .app_data() 代替 data
            .app_data(counter.clone()) // <- 注册创建的data
            .route("/", web::get().to(index))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```

## 使用一个应用级Scope去组合应用(Using an Application Scope to Compose Applications)
`web::scope()` 方法允许你设置一个资源组前缀. 它表示所有资源类型(或者说是一组资源定位符)前缀配置. 

比如说:

```rust
#[actix_web::main]
async fn main() {
    let scope = web::scope("/users").service(show_users);
    App::new().service(scope);
}
```

在上面的示例中, `show_users` 路由将是具有 `/users/show` 而不是 `/show` 路径的有效路由模式, 因为应用程序的scope参数被添加到该模式之前.
所以只有在URL路径为 `/users/show` 时, 路由才会匹配, 当使用路由名称 `show_users` 调用 `HttpRequest.url_for()` 函数时, 它也会生成同样的
URL路径.

## 应用防护和虚拟主机(Application guards and virtual hosting)
其实"防护"(guards)可以是说是actix-web为handler函数提供的一种安全配置.

你可以将防护看成一个接收请求对象引用并返回ture或者false的简单函数. 可以说guard是实现了Guard trait的任何对象. `actix-web` 提供了几种开箱即用的 `guards`.
你可以查看 [functions section](https://docs.rs/actix-web/3/actix_web/guard/index.html#functions) API文档.

其中一个guards就是 `Header`. 它可以被用在请求头信息的过滤.
```rust
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(
                web::scope("/")
                    .guard(guard::Header("Host", "www.rust-lang.org"))
                    .route("", web::to(|| HttpResponse::Ok().body("www"))),
            )
            .service(
                web::scope("/")
                    .guard(guard::Header("Host", "users.rust-lang.org"))
                    .route("", web::to(|| HttpResponse::Ok().body("user"))),
            )
            .route("/", web::to(|| HttpResponse::Ok()))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```

## 可配置(Configure)
为了简单与可重用, `App` 与 `web::Scope` 两者都提供了 `configure` 方法. 此功能让配置的各个部分在不同的模块甚至不同的库(library)
中移动时非常有用. 比如说, 一些资源的配置可以被移动到不同的模块中.

(译者注: 其实这是一种拆分管理,一般来说可以提高代码重用,减少修改某个Scope组时可能带来的影响其它模块的错误.)

```rust
use actix_web::{web, App, HttpResponse, HttpServer};

// 此功能可以位于其他模块中
fn scoped_config(cfg: &mut web::ServiceConfig) {
    cfg.service(
        web::resource("/test")
            .route(web::get().to(|| HttpResponse::Ok().body("test")))
            .route(web::head().to(|| HttpResponse::MethodNotAllowed())),
    );
}

// 此功能可以位于其他模块中
fn config(cfg: &mut web::ServiceConfig) {
    cfg.service(
        web::resource("/app")
            .route(web::get().to(|| HttpResponse::Ok().body("app")))
            .route(web::head().to(|| HttpResponse::MethodNotAllowed())),
    );
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .configure(config)
            .service(web::scope("/api").configure(scoped_config))
            .route("/", web::get().to(|| HttpResponse::Ok().body("/")))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```
上面例子的结果是:
```text
/         -> "/"
/app      -> "app"
/api/test -> "test"
```

每一个 `ServiceConfig` 都有它自己的 `data`, `routers`, 和 `services`.

================================================
FILE: doc/AutoReloading.md
================================================
## 自动重载开发服务(Auto-Reloading Development Server)

在开发的过程中,让**Cargo**在代码发生变化时自动编译是非常方便的. 可以使用 [cargo-watch](https://github.com/passcod/cargo-watch) 非常
容易的来完成这件事.

```shell
cargo watch -x 'run --bin app'
```

## 值得注意点(Historical Note)

此页面的旧版本建议使用`systemfd`和`listenfd`的组合,但这也有些缺陷,很难正确的整合,尤其是在更广泛的开发工作流中. 我们考虑使用 `cargo-watch`
可以非常方便的达到自动重载(auto-reloading)的目的.



================================================
FILE: doc/ConnectionLifecycle.md
================================================
# 链接生命周期(Connection Lifecycle)

## 架构总览(Architecture overview)
在服务启动并监听所有socket链接后, `Accept` 和 `Worker` 两个主要的轮循是来处理从客户端传入的链接的.

一旦接受链接, 应用程序级协议处理就会从 `Worker` 派生(spawn)的指定 `Dispatcher` 循环中发生.

![](../images/connection_overview.svg)

## Accept循环的更多细节 (Accept loop in more detail)

![](../images/connection_accept.svg)

关于更多 [Accept](https://github.com/actix/actix-net/blob/master/actix-server/src/accept.rs) 结构体
代码的实现, 请参考 [actix-server](https://crates.io/crates/actix-server) 包.

## Worker循环的更多细节(Worker loop in more detail)

![](../images/connection_worker.svg)

关于更多 [Worker](https://github.com/actix/actix-net/blob/master/actix-server/src/worker.rs) 结构体
代码的实现, 请参考 [actix-server](https://crates.io/crates/actix-server) 包.

## 请求循环大体过程(Request loop roughly)

![](../images/connection_request.svg)

更多请求循环的代码实现请参考 [actix-web](https://crates.io/crates/actix-web) 与 [actix-http](https://crates.io/crates/actix-http)
这两个包.

================================================
FILE: doc/Databases.md
================================================
## 异步选项(Async Options)
我们(actix-web)提供了几个使用异步数据库适配器的示例工程:
* SQLx: https://github.com/actix/examples/tree/master/sqlx_todo
* Postgres: https://github.com/actix/examples/tree/master/async_pg
* SQLite: https://github.com/actix/examples/tree/master/async_db

## Diesel
Diesel的当前版本(v1)还不支持异步操作, 因此使用 `web::block` 函数将数据库操作装载到 _Actix_ 运行时线程池中是非常重要的.

你可以创建与应用程序在数据库上执行的所有操作相对应的动作功能.
```rust
fn insert_new_user(db: &SqliteConnection, user: CreateUser) -> Result<User, Error> {
    use self::schema::users::dsl::*;

    // 创建插入模型
    let uuid = format!("{}", uuid::Uuid::new_v4());
    let new_user = models::NewUser {
        id: &uuid,
        name: &user.name,
    };

    // 正常 diesel 操作
    diesel::insert_into(users)
        .values(&new_user)
        .execute(&self.0)
        .expect("Error inserting person");

    let mut items = users
        .filter(id.eq(&uuid))
        .load::<models::User>(&self.0)
        .expect("Error loading person");

    Ok(items.pop().unwrap())
}
```

现在你应该使用例如像 `r2d2` 这样的包来设置数据库链接池, 这将使你的应用程序有许多数据库链接可用. 这也意味着多个处理函数可以同时操作数据库,
并且还能够接收新的链接. 简单的来说链接池是应用程序状态. 在这种情况下最好不要使用状态包装结构体(struct), 因为在池中会共享访问.

```rust
type DbPool = r2d2::Pool<ConnectionManager<SqliteConnection>>;

#[actix_web::main]
async fn main() -> io::Result<()> {
    // 创建链接池
    let pool = r2d2::Pool::builder()
        .build(manager)
        .expect("Failed to create pool.");

    // 启动HTTP服务
    HttpServer::new(move || {
        App::new::data(pool.clone())
            .resource("/{name}", web::get().to(index))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```

现在, 在请求处理器中使用 `Data<T>` 提取器来从应用程序State中得到pool并进而得到链接. 这提供了一个可以传入到 `web::block` 闭包中的数据库链接.
然后只需要使用必要的参数调用 action 函数, `.await` 结果即可.

如果你返回了一个实现了 `ResponseError` 的错误类型, 示例中在使用 `?` 号操作符前将一个错误映射成一个 `HttpResponse` 中时, 这个操作并不是必须的.

```rust
async fn index(req: web::Data<DbPool>, name: web::Path<(String)>) -> impl Responder {
    let name = name.into_inner();

    let conn = pool.get().expect("couldn't get db connection from pool");

    let user = web::block(move || actions::insert_new_user(&conn, &user))
        .await
        .map_err(|e| {
            eprintln!("{}", e);
            HttpResponse::InternalServerError().finish()
        })?;
    
    Ok(HttpResponse::Ok().json(user))
}
```

完整的示例参考这里: https://github.com/actix/examples/tree/master/diesel

================================================
FILE: doc/Errors.md
================================================
## 错误(Errors)
Actix-web使用它自己的`actix_web::error::Error`类型和`actix_web::error:ResponseError` trait 来处理web处理函数中的错误.

如果一个处理函数在一个`Result`中返回`Error`(指普通的Rust trait `std::error:Error`),此`Result`也实现了`ResponseError` trait的话,
actix-web将使用相应的`actix_web::http::StatusCode` 响应码作为一个Http response响应渲染.默认情况下会生成内部服务错误:
```rust
pub trait ResponseError {
    fn error_response(&self) -> Response<Body>;
    fn status_code(&self) -> StatusCode;
}
```
`Response` 将兼容的 `Result` 强制转换到Http响应中:
```rust
impl<T: Responder, E: Into<Error>> Responder for Result<T, E>{}
```
上面代码中的`Error`是actix-web中的error定义, 并且任何实现了`ResponseError`的错误都会被自动转换.

Actix-web提供了一些常见的非actix error的 `ResponseError` 实现. 例如一个处理函数返回一个 `io::Error`,那么这个错误将会被自动的转换成一个
`HttpInternalServerError`:
```rust
use std::io;
use actix_files::NamedFile;

fn index(_req: HttpRequest) -> io::Result<NamedFile> {
    Ok(NamedFile::open("static/index.html"))
}
```
参见完整的 `ResponseError` 外部实现[the actix-web API documentation](https://docs.rs/actix-web/3/actix_web/error/trait.ResponseError.html#foreign-impls)

## 自定义错误响应示例(An example of a custom error response)
这里有一个实现了`ResponseError`的示例, 使用`derive_more`声明错误枚举.

```rust
use actix_web::{error, Result};
use derive_more::{Display, Error};

#[derive(Debug, Display, Error)]
#[display(fmt = "my error: {}", name)]
struct MyError {
    name: &'static str,
}

// Use default implementation for `error_response()` method
// 为 `error_response()` 方法使用默认实现
impl error::ResponseError for MyError {}

async fn index() -> Result<&'static str, MyError> {
    Err(MyError { name: "test" })
}
```
当上面的 `index` 处理函数执行时, `ResponseError` 的一个默认实现 `error_response()` 会渲染500(服务器内部错误)返回.

重写 `error_response()` 方法来产生更多有用的结果:

```rust
use actix_web::{
    dev::HttpResponseBuilder, error, get, http::header, http::StatusCode, App, HttpResponse,
};
use derive_more::{Display, Error};

#[derive(Debug, Display, Error)]
enum MyError {
    #[display(fmt = "internal error")]
    InternalError,

    #[display(fmt = "bad request")]
    BadClientData,

    #[display(fmt = "timeout")]
    Timeout,
}

impl error::ResponseError for MyError {
    fn error_response(&self) -> HttpResponse {
        HttpResponseBuilder::new(self.status_code())
            .set_header(header::CONTENT_TYPE, "text/html; charset=utf-8")
            .body(self.to_string())
    }

    fn status_code(&self) -> StatusCode {
        match *self {
            MyError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
            MyError::BadClientData => StatusCode::BAD_REQUEST,
            MyError::Timeout => StatusCode::GATEWAY_TIMEOUT,
        }
    }
}

#[get("/")]
async fn index() -> Result<&'static str, MyError> {
    Err(MyError::BadClientData)
}
```

## 错误帮助(Error helpers)
Actix-web提供了一个错误帮助功能的集合, 这个集合在从其它错误生成指定的HTTP错误码时非常有用.下面我们转换 `MyError`, 它没有实现
`ResponseError` trait, 使用`map_err`来返回400(bad request):

```rust
use actix_web::{error, get, App, HttpServer, Result};

#[derive(Debug)]
struct MyError {
    name: &'static str,
}

#[get("/")]
async fn index() -> Result<&'static str> {
    let result: Result<&'static str, MyError> = Err(MyError { name: "test error" });

    Ok(result.map_err(|e| error::ErrorBadRequest(e.name))?)
}
```
查看[The documentation for actix-web's `error` `module` ](https://docs.rs/actix-web/3/actix_web/error/struct.Error.html)
了解完整的错误帮助清单.

## 错误日志(Error logging)
Actix 所有错误日志都是 `WARN` 级别的. 如果应用日志级别启用 `DEBUG` 和 `RUST_BACKTRACE`, 回溯日志也会被启用.这些可以使用环境变量进行配置:
```text
RUST_BACKTRACE=1 RUST_LOG=actix_web=debug cargo run
```
使用 error backtrace 的`Error`类型如果可用. 如果底层的异常(failure)(译者注: 这里翻译成异常好点) 不提供回溯(backtrace),则构造一个新的回溯,指向发生转换的点(而不是错误的根源).

## 错误处理的最佳实践(Recommended practices in error handling).
考虑将应用产生的错误分成两个大类是非常有用的: 这意味着一部分面向用户,另外一部分则不是.

前者的一个示例是, 我们可以使用失败来批定个 `UserError` 的枚举, 该枚举封装了一个 `ValidationError` , 以便在用户输入错误时返回: 

```rust
use actix_web::{
    dev::HttpResponseBuilder, error, get, http::header, http::StatusCode, App, HttpResponse,
    HttpServer,
};
use derive_more::{Display, Error};

#[derive(Debug, Display, Error)]
enum UserError {
    #[display(fmt = "Validation error on field: {}", field)]
    ValidationError { field: String },
}

impl error::ResponseError for UserError {
    fn error_response(&self) -> HttpResponse {
        HttpResponseBuilder::new(self.status_code())
            .set_header(header::CONTENT_TYPE, "text/html; charset=utf-8")
            .body(self.to_string())
    }
    fn status_code(&self) -> StatusCode {
        match *self {
            UserError::ValidationError { .. } => StatusCode::BAD_REQUEST,
        }
    }
}
```
这将完全按预期的方式运行, 因为编写使用 `display` 定义的错误消,其目的是为了用户要明确读取.

然而, 并不是所有的错误都要返回 - 在服务端环境捕获的许多异常我们都想让它对用户是隐藏的(不展示给用户看). 例如, 数据库关闭了导致的客户端
连接超时, 或 HTML 模板渲染时的格式错误. 在这些情况下最好将错误映射为适合用户使用的一般错误.

下面的示例,将内部错误映射为一个面向用户的 `InternalError`.

```rust
use actix_web::{
    dev::HttpResponseBuilder, error, get, http::header, http::StatusCode, App, HttpResponse,
    HttpServer,
};
use derive_more::{Display, Error};

#[derive(Debug, Display, Error)]
enum UserError {
    #[display(fmt = "An internal error occurred. Please try again later.")]
    InternalError,
}

impl error::ResponseError for UserError {
    fn error_response(&self) -> HttpResponse {
        HttpResponseBuilder::new(self.status_code())
            .set_header(header::CONTENT_TYPE, "text/html; charset=utf-8")
            .body(self.to_string())
    }
    fn status_code(&self) -> StatusCode {
        match *self {
            UserError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
        }
    }
}

#[get("/")]
async fn index() -> Result<&'static str, UserError> {
    do_thing_that_fails().map_err(|_e| UserError::InternalError)?;
    Ok("success!")
}
```
通过将错误划分为面向用户的与非面向用户的部分, 我们可以确保我们不会意外的将应用程序内部错误暴露给用户,因为这部分错误并不是用户想看到的.

## 错误日志(Error Logging)
使用 `middleware::Logger` 示例:
```rust
use actix_web::{error, get, middleware::Logger, App, HttpServer, Result};
use log::debug;
use derive_more::{Display, Error};

#[derive(Debug, Display, Error)]
#[display(fmt = "my error: {}", name)]
pub struct MyError {
    name: &'static str,
}

// Use default implementation for `error_response()` method
impl error::ResponseError for MyError {}

#[get("/")]
async fn index() -> Result<&'static str, MyError> {
    let err = MyError { name: "test error" };
    debug!("{}", err);
    Err(err)
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    std::env::set_var("RUST_LOG", "my_errors=debug,actix_web=info");
    std::env::set_var("RUST_BACKTRACE", "1");
    env_logger::init();

    HttpServer::new(|| App::new().wrap(Logger::default()).service(index))
        .bind("127.0.0.1:8080")?
        .run()
        .await
}
```



================================================
FILE: doc/Extractors.md
================================================
## 类型安全的信息提取器(Type-safe information extractor)
`actix-web` 提供了一个灵活的类型安全的请求信息访问者,它被称为提取器(extractors)(实现了 `impl FromRequest`).
默认下actix-web提供了几种extractors的实现.

提取器可以被作为处理函数的参数访问. `actix-web` 每个处理函数(handler function)最多支持10个提取器. 它们作为参数的位置没有影响.
```rust
async fn index(path: web::Path<(String, String)>, json: web::Json<MyInfo>) -> impl Responder {
    let path = path.into_inner();
    format!("{} {} {} {}", path.0, path.1, json.id, json.username)
}
```

# 路径(Path)
Path提供了能够从请求路径中提取信息的能力. 你可以从path中反序列化成任何变量.

因此,注册一个/users/{user_id}/{friend}的路径, 你可以反序列化两个字段, user_id和 friend.
这些字段可以被提取到一个 `tuple` (元组)中去, 比如: Path<u32, String> 或者是任何实现了 `serde trait`包中的 `Deserialize`
的结构体(structure)

请参见下面的示例:
```rust
use actix_web::{get, web, Result};

/// 从 path url "/users/{user_id}/{friend}" 中提取参数
/// {user_id} - 反序列化为一个 u32
/// {friend} - 反序列化为一个 String
#[get("/users/{user_id}/{friend}")] // <- 定义路径参数
async fn index(web::Path((user_id, friend)): web::Path<(u32, String)>) -> Result<String> {
    Ok(format!("Welcome {}, user_id {}!", friend, user_id))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    use actix_web::{App, HttpServer};

    HttpServer::new(|| App::new().service(index))
        .bind("127.0.0.1:8080")?
        .run()
        .await
}
```


也可以提取信息到一个指定的实现了`serde trait`反序列化的类型中去. 这种serde的使用方式与使用元组等效.


另外你也可以使用 `get` 或者 `query` 方法从请求path中通过名称提取参数值:
```rust
#[get("/users/{userid}/{friend}")] // <- 定义路径参数
async fn index(req: HttpRequest) -> Result<String> {
    let name: String = req.match_info().get("friend").unwrap().parse().unwrap();
    let userid: i32 = req.match_info().query("userid").parse().unwrap();

    Ok(format!("Welcome {}, userid {}!", name, userid))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    use actix_web::{App, HttpServer};

    HttpServer::new(|| App::new().service(index))
        .bind("127.0.0.1:8080")?
        .run()
        .await
}
```

## 查询(Query)
查询 `Query` 类型为请求参数提供了提取功能. 底层是使用了 `serde_urlencoded` 包功能.

```rust
use actix_web::{get, web, App, HttpServer};
use serde::Deserialize;

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

// 仅仅在请求查询参数中有 'username' 字段时才会被调用
#[get("/")]
async fn index(info: web::Query<Info>) -> String {
    format!("Welcome {}!", info.username)
}
```

## Json
`Json`提取器允许你将请求body中的信息反序列化到一个结构体中. 为了从请求body中提取类型的信息,类型 T 必须要实现 `serde` 的 `Deserialize trait`.

参考如下示例:
```rust
use actix_web::{get, web, App, HttpServer, Result};
use serde::Deserialize;

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

/// 将request body中的信息反序列化到 Info 结构体中去
#[get("/")]
async fn index(info: web::Json<Info>) -> Result<String> {
    Ok(format!("Welcome {}!", info.username))
}
```
一些提取器提供了一种可以配置提取过程的方式. `Json` 提取器就使用 `JsonConfig` 类来配置. 为了配置提取器,可以将配置对象通过`resource`的`.data()`
方法传进去.如果是Json提取器,它将返回一个 `JsonConfig`. 另外你也可以配置json的最大有效负载(playload)和自定义错误处理功能.

下面的示例限制了`playload`的最大大小为4kb,且使用一个自定义的`error`处理.
```rust
use actix_web::{error, web, App, FromRequest, HttpResponse, HttpServer, Responder};
use serde::Deserialize;

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

/// 反序列化request body中的信息到 Info结构体中,且设置 playload大小为 4kb
async fn index(info: web::Json<Info>) -> impl Responder {
    format!("Welcome {}!", info.username)
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        // 配置json提取器
        let json_config = web::JsonConfig::default()
            .limit(4096)
            .error_handler(|err, _req| {
                // 创建一个自定义的错误类型
                error::InternalError::from_response(err, HttpResponse::Conflict().finish()).into()
            });

        App::new().service(
            web::resource("/")
                // 通过.app_data()改变json 提取器配置
                .app_data(json_config)
                .route(web::post().to(index)),
        )
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```

## 表单(Form)
当前仅支持url编码的形式. 使用`url-encoded`的body能被提取成一个指定的类型.这个类型必须实现`serde`包的`Deserialize trait`.

`FormConfig` 允许你配置提取的过程.

参考如下示例:
```rust
use actix_web::{post, web, App, HttpServer, Result};
use serde::Deserialize;

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

/// 使用serde提取表单数据
/// 仅当 content type 类型是  *x-www-form-urlencoded* 是 handler处理函数才会被调用
/// 且请求中的内容能够被反序列化到一个 "FormData" 结构体中去.
#[post("/")]
async fn index(form: web::Form<FormData>) -> Result<String> {
    Ok(format!("Welcome {}!", form.username))
}
```

## 其它(Other)
`Actix-web` 也提供了一些其它的提取器(extractors):
* [Data](https://docs.rs/actix-web/3/actix_web/web/struct.Data.html) - 如果你需要访问应用程序状态的话.
* HttpRequest - 如果你需要访问请求, `HttpRequest`本身就是一个提取器,它返回Self.
* String - 你可以转换一个请求的`playload`成一个`String`. 可以参考文档中的[example](https://docs.rs/actix-web/3/actix_web/trait.FromRequest.html#example-2)
* bytes::`Bytes` - 你可以转换一个请求的`playload`到`Bytes`中. 可以参考文档中的[example](https://docs.rs/actix-web/3/actix_web/trait.FromRequest.html#example-4)
* Playload - 可以访问请求中的playload. [example](https://docs.rs/actix-web/3/actix_web/web/struct.Payload.html)

## 应用程序状态提取器(Application state extractor)
可以使用 `web::Data` 提取器在handler函数中访问应用程序状态(state); 然而state仅能作为一个只读引用来访问.如果你需要以可变(mutable)的方式
来访问state, 则它必须被实现.

**Beware**, actix为应用程序状态和处理函数创建多个副本. 它为每一个线程创建一个副本.

下面是存储了处理的请求数的处理程序示例:

```rust
use actix_web::{web, Responder};
use std::cell::Cell;

#[derive(Clone)]
struct AppState {
    count: Cell<i32>,
}

async fn show_count(data: web::Data<AppState>) -> impl Responder {
    format!("count: {}", data.count.get())
}

async fn add_one(data: web::Data<AppState>) -> impl Responder {
    let count = data.count.get();
    data.count.set(count + 1);

    format!("count: {}", data.count.get())
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    use actix_web::{App, HttpServer};

    let data = AppState {
        count: Cell::new(0),
    };

    HttpServer::new(move || {
        App::new()
            .data(data.clone())
            .route("/", web::to(show_count))
            .route("/add", web::to(add_one))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```
虽然处理函数可以工作,`self.0` 的值会有所不同,具体取决于线程数量和每个线程处理的请求数.正解的实现是使用`Arc` 和 `ActomicUsize` .
(因为它们是线程安全的).

```rust
use actix_web::{get, web, App, HttpServer, Responder};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::Arc;

#[derive(Clone)]
struct AppState {
    count: Arc<AtomicUsize>,
}

#[get("/")]
async fn show_count(data: web::Data<AppState>) -> impl Responder {
    format!("count: {}", data.count.load(Ordering::Relaxed))
}

#[get("/add")]
async fn add_one(data: web::Data<AppState>) -> impl Responder {
    data.count.fetch_add(1, Ordering::Relaxed);

    format!("count: {}", data.count.load(Ordering::Relaxed))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let data = AppState {
        count: Arc::new(AtomicUsize::new(0)),
    };

    HttpServer::new(move || {
        App::new()
            .data(data.clone())
            .service(show_count)
            .service(add_one)
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```
小心使用这些同步原语像`Mutex` 或 `Rwlock` . `actix-web` 框架是异步处理请求的. 如果阻塞了执行线程,那么所有的并发请求都将在处理函数
阻塞. 如果你需要在多线程中共享或更新状态, 考虑使用`tokio`的同步原语.



================================================
FILE: doc/GettingStarted.md
================================================
## 安装Rust(Installing Rust)
如果你还没有安装Rust, 我们建议你使用 `rustup` 来管理你的Rust安装. [official rust guide](https://doc.rust-lang.org/book/ch01-01-installation.html) 
提供了精彩的安装起步指导.

Actix Web 当前支持的Rust最低版本(MSRV) 是1.42. 执行 `rustup update` 命令Rust可用的最佳版本. 因此本指南假设你在 Rust 1.42或更高的版本上运行.

## Hello, world!
基于Cargo 命令创建一个新的字节码工程, 并转换到新的目录:

```shell script
cargo new hello-world
cd hello-world
```
在你的工程下的 `Cargo.toml` 文件内添加 `Actix-web` 的依赖.
```toml
[depandencies]
actix-web = "3"
```

使用异步函数的请求处理器接受零个或多个参数. 这些参数能从请求中提取(查看 `FromRequest` trait) 且返回一个能被转换成一个 `HttpResponse`
(查看 `Responder` trait) 的类型.

```rust
use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder};

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

#[post("/echo")]
async fn echo(req_body: String) -> impl Responder {
    HttpResponse::Ok().body(req_body)
}

async fn manual_hello() -> impl Responder {
    HttpResponse::Ok().body("Hey there!")
}
```

注意,其中某些处理器使用内置宏直接附加了路由信息. 这就允许你指定处理器程序响应的方法与路径. 你也将在下面的示例中看到如何不使用路由宏来注册
一个其它的路由.

下一步,创建一个 `App` 实例并注册请求处理器. 为使用了路由宏的处理器来使用 `App::service` 方法设置(路由), 并且 `App::route` 可以手动的
注册路由处理器,并声明一个路径(path)和方法(译者注: 比如post或者get). 最后应用程序使用 `HttpServer` 来启动, 它将使你的 `App` 作为一个
"application factory" 来处理传入的请求.

```rust
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(hello)
            .service(echo)
            .route("/hey", web::get().to(manual_hello))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```

使用 `Cargo run` 来编译并运行程序. 使用actix运行时的 `#[actix_web::main]` 宏用来执行异步main函数. 现在你可以访问 `http://localhost:8080/` 
或者任何一个你定义的路由来查看结果.


================================================
FILE: doc/HTTP2.md
================================================
## HTTP2.0
如果有可能 `actix-web` 会自动的将链接升级成 _HTTP/2_ .

## Negotiation
_HTTP/2_ 协议是基于TLS的且需要 [TLS ALPN](https://tools.ietf.org/html/rfc7301).

当前仅有 `rust-openssl` 有支持.

`alpn` 需要协商启用该功能, 当启用时, `HttpServer` 提供了一个 [bind_openssl](https://docs.rs/actix-web/3/actix_web/struct.HttpServer.html#method.bind_openssl)
的方法来操作.

toml文件中加入如下依赖:

```toml
actix-web = { version = "3", features = ["openssl"] }
openssl = { version = "0.10", features = ["v110"] }
```

```rust
use actix_web::{web, App, HttpRequest, HttpServer, Responder};
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};

async fn index(_req: HttpRequest) -> impl Responder {
    "Hello."
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // 载入 ssl keys
    // 为测试创建自签名临时证书:
    // `openssl req -x509 -newkey rsa:4096 -nodes -keyout key.pem -out cert.pem -days 365 -subj '/CN=localhost'`
    let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
    builder
        .set_private_key_file("key.pem", SslFiletype::PEM)
        .unwrap();
    builder.set_certificate_chain_file("cert.pem").unwrap();

    HttpServer::new(|| App::new().route("/", web::get().to(index)))
        .bind_openssl("127.0.0.1:8080", builder)?
        .run()
        .await
}
```
不支持升级到RFC3.2节中描述的HTTP/2.0模式. _HTTP/2_ 明文链接与TLS链接都支持.

具体示例参考 [examples/tls](https://github.com/actix/examples/tree/master/rustls).

================================================
FILE: doc/HTTPServerInitialization.md
================================================
## 架构总览(Architecture overview)
下面的图表是 HttpServer 初始化过程, 它发生在如下代码处理过程中:

```rust
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .route("/", web::to(|| HttpResponse::Ok()))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```

![](../images/http_server.svg)

================================================
FILE: doc/Handlers.md
================================================
## 请求处理器(Request Handlers)
一个请求处理器,它是一个异步函数,可以接收零个或多个参数,而这些参数被实现了(比如, [impl FromRequest](https://docs.rs/actix-web/3/actix_web/trait.FromRequest.html) )的请求所提取,
并且返回一个被转换成HttpResponse或者其实现(比如, [impl Responder](https://docs.rs/actix-web/3/actix_web/trait.Responder.html) )的类型.

请求处理发生在两个阶段.首先处理对象被调用,并返回一个实现了 `Responder` trait的任何对象.然后在返回的对象上调用 `respond_to()` 方法,将其
自身转换成一个 `HttpResponse` 或者 `Error` .

默认情况下 _actix-web_ 为 `&‘static str` , `String` 等提供了 `Responder` 的标准实现.

完整的实现清单可以参考 [Responder documentation](https://docs.rs/actix-web/3/actix_web/trait.Responder.html#foreign-impls) .

有效的 handler示例:

```rust
async fn index(_req: HttpRequest) -> &'static str {
    "Hello World"
}
async fn index_two(_req: HttpRequest) -> String {
    "Hello world".to_string()
}
```

你也可以改变返回的签名为 `impl Responder` 它在要返回复杂类型时比较好用.

```rust
async fn index(_req: HttpRequest) -> impl Responder {
    Bytes::from_static(b"Hello world")
}
```

```rust
async fn index(_req: HttpRequest) -> impl Responder {
    // ...
}
```

## 返回自定义类型(Response with custom Type)
为了想直接从处理函数返回自定义类型的话, 需要这个类型实现 `Responder` trait.

让我们创建一个自定义响应类型,它可以序列化为一个 `application/json` 响应.

```rust
use actix_web::{Error, HttpRequest, HttpResponse, Responder};
use serde::Serialize;
use futures::future::{ready, Ready};

#[derive(Serialize)]
struct MyObj {
    name: &'static str,
}

// Responder
impl Responder for MyObj {
    type Error = Error;
    type Future = Ready<Result<HttpResponse, Error>>;

    fn respond_to(self, _req: &HttpRequest) -> Self::Future {
        let body = serde_json::to_string(&self).unwrap();

        // 创建响应并设置Content-Type
        ready(Ok(HttpResponse::Ok()
            .content_type("application/json")
            .body(body)))
    }
}

async fn index() -> impl Responder {
    MyObj { name: "user" }
}
```

## 流式响应body(Streaming response body)
响应主体也可以异步生成. 在下面的案例中, body 必须实现 Steam trait `Stream<Item=Bytes, Error=Error>` , 比如像下面这样:

```rust
use actix_web::{get, App, Error, HttpResponse, HttpServer};
use bytes::Bytes;
use futures::future::ok;
use futures::stream::once;

#[get("/stream")]
async fn stream() -> HttpResponse {
    let body = once(ok::<_, Error>(Bytes::from_static(b"test")));

    HttpResponse::Ok()
        .content_type("application/json")
        .streaming(body)
}

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

## 不同的返回类型(两种) (Different Return Types(Either))
有时候你需要在响应中返回两种不同的类型, 例如,你可以进行错误检查并返回错误,返回异步响应或需要两种不同类型的任何结果.

对于这种情况, 你可以使用 `Either` 类型. `Either` 允许你组合两个不同类型的responder到一个单个类型中去.

请看如下示例:

```rust
use actix_web::{Either, Error, HttpResponse};

type RegisterResult = Either<HttpResponse, Result<&'static str, Error>>;

async fn index() -> RegisterResult {
    if is_a_variant() {
        // <- 变体 A
        Either::A(HttpResponse::BadRequest().body("Bad data"))
    } else {
        // <- 变体 B
        Either::B(Ok("Hello!"))
    }
}
```
(译者注: 相当于将不同分支的不同类型包装到某一个类型中再返回).

================================================
FILE: doc/Middleware.md
================================================
## 中间件(Middleware)

Actix-web 的中间件系统允许我们在请求/响应处理时添加一些其它的行为. 中间件可以(hook into)挂接到进入的请求处理过程中. 使我们能修改请求以及
暂停请求处理来及早的返回响应.

中间件也可以挂接(hook into)响应处理过程中.

一般来说, 中间件参与以下操作:

- 请求预处理.
- 响应后置处理.
- 修改应用程序状态.
- 访问扩展服务(redis, logging, sessions).

每个 `App` , `scope`, `Resource` 都能注册中间件, 并且它以注册顺序相反的顺序来执行. 通常, 中间件是一种实现了 [Service trait](https://docs.rs/actix-web/3/actix_web/dev/trait.Service.html)
和 [Transform trait](https://docs.rs/actix-web/3/actix_web/dev/trait.Transform.html) 的类型. 在 trait 中的每一个方法都有其默认实现.
每一个方法能立即返回一个结果或者一个 _future_ 对象.

下面演示创建一个简单的中间件:

```rust
use std::pin::Pin;
use std::task::{Context, Poll};

use actix_service::{Service, Transform};
use actix_web::{dev::ServiceRequest, dev::ServiceResponse, Error};
use futures::future::{ok, Ready};
use futures::Future;

/// 在中间件处理过程器有两步.
/// 1. 中间件初始化, 下一个服务链中作为一个参数中间件工厂被调用.
/// 2. 中间件的调用方法被正常的请求调用.
pub struct SayHi;

///中间件工厂是来自 actix_service 包下的一个 `Transform` trait.
/// `S` - 下一个服务类型
/// `B` - 响应body类型
impl<S, B> Transform<S> for SayHi
where
    S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
    S::Future: 'static,
    B: 'static,
{
    type Request = ServiceRequest;
    type Response = ServiceResponse<B>;
    type Error = Error;
    type InitError = ();
    type Transform = SayHiMiddleware<S>;
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ok(SayHiMiddleware { service })
    }
}

pub struct SayHiMiddleware<S> {
    service: S,
}

impl<S, B> Service for SayHiMiddleware<S>
where
    S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
    S::Future: 'static,
    B: 'static,
{
    type Request = ServiceRequest;
    type Response = ServiceResponse<B>;
    type Error = Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.service.poll_ready(cx)
    }

    fn call(&mut self, req: ServiceRequest) -> Self::Future {
        println!("Hi from start. You requested: {}", req.path());

        let fut = self.service.call(req);

        Box::pin(async move {
            let res = fut.await?;

            println!("Hi from response");
            Ok(res)
        })
    }
}
```

另外对于简单的使用示例, 你可以使用 [wrap_fn](https://docs.rs/actix-web/3/actix_web/struct.App.html#method.wrap_fn) 来创建一个小的临时的中间件:

```rust
use actix_service::Service;
use actix_web::{web, App};
use futures::future::FutureExt;

#[actix_web::main]
async fn main() {
    let app = App::new()
        .wrap_fn(|req, srv| {
            println!("Hi from start. You requested: {}", req.path());
            srv.call(req).map(|res| {
                println!("Hi from response");
                res
            })
        })
        .route(
            "/index.html",
            web::get().to(|| async {
                "Hello, middleware!"
            }),
        );
}
```

Actix-web 提供了一些有用的中间件, 比如, `logging`, `user sessions`, `Compress` 等等.

## 日志(Logging)

日志被作为一种中间件来实现. 常见的做法是将日志中间件注册为应用程序第一个中间件. 必须为每个应用程序注册日志中间件.

`Logger` 中间件使用标准的日志包去记录日志信息. 为了查看日志你必须为 _actix_web_ 包启用日志功能. ([env_logger](https://docs.rs/env_logger/*/env_logger/) 或者其它的).

## 用法(Usage)

创建指定格式的 `Logger` 中间件. 可以使用默认 `default` 方法创建默认的 `Logger`, 它使用默认的格式:

```text
  %a %t "%r" %s %b "%{Referer}i" "%{User-Agent}i" %T
```

```rust
use actix_web::middleware::Logger;
use env_logger::Env;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    use actix_web::{App, HttpServer};

    env_logger::from_env(Env::default().default_filter_or("info")).init();

    HttpServer::new(|| {
        App::new()
            .wrap(Logger::default())
            .wrap(Logger::new("%a %{User-Agent}i"))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```

下面是默认情况下日志的记录格式:

```text
INFO:actix_web::middleware::logger: 127.0.0.1:59934 [02/Dec/2017:00:21:43 -0800] "GET / HTTP/1.1" 302 0 "-" "curl/7.54.0" 0.000397
INFO:actix_web::middleware::logger: 127.0.0.1:59947 [02/Dec/2017:00:22:40 -0800] "GET /index.html HTTP/1.1" 200 0 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.13; rv:57.0) Gecko/20100101 Firefox/57.0" 0.000646
```

## 格式(Format)

- %% - %号标识
- %a - 远程 IP 地址(如果使用了反向代码,则为代理的 IP)
- %t - 当请求开始处理的时间
- %P - 请求子服务进程 ID 号
- %r - 请求的第一行
- %s - 响应状态码
- %b - 包含 http 响应头的响应字节大小
- %T - 服务请求所用的时间, 以秒为单位, 以.06f 为浮点数格式
- %D - 服务请求所有时间, 以毫秒为单位
- %{FOO}i - 请求 header 中的["FOO"] (译者注: 这相当于可以在日志中取到自定义请求头中的内容)
- %{FOO}o - 响应 header 中的["FOO"] (译者注: 这相当于可以在日志中取到自定义响应头中的内容)
- %{FOO} - 系统环境中["FOO"]

## 默认头(Default headers)

为了设置默认响应头, `DefaultHeaders` 中间件可以被使用. 如果响应中已经包含了指定的响应头,则 _DefaultHeaders_ 中间件不会再次设置头.

```rust
use actix_web::{http, middleware, HttpResponse};

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    use actix_web::{web, App, HttpServer};

    HttpServer::new(|| {
        App::new()
            .wrap(middleware::DefaultHeaders::new().header("X-Version", "0.2"))
            .service(
                web::resource("/test")
                    .route(web::get().to(|| HttpResponse::Ok()))
                    .route(
                        web::method(http::Method::HEAD)
                            .to(|| HttpResponse::MethodNotAllowed()),
                    ),
            )
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```

## 用户会话(User sessions)

Actix-web 提供了会话管理的通用解决方案. [actix-session](https://docs.rs/actix-session/0.3.0/actix_session/) 中间件可以使用多种
后端类型来存储 session 数据.

默认情况下, 仅 cookie 会话后端被实现. 可以添加其它后端的实现.

[CookieSession](https://docs.rs/actix-session/0.3.0/actix_session/struct.CookieSession.html) 使用 cookie 作为会话存储.
`CookieSessionBackend` 创建的 session 仅限制用来存少于 4000 字节的数据, 因为 payload 必须适合单个 cookie. 如果 session 包含了超过 4000
字节的数据, 就会产生一个内部服务错误.

cookie 可能要有签名的或者私有的安全策略. 每种都由各自的 `CookieSession` 构建函数来创建.

一个签名的 cookie 可以被客户端查看,但不能被修改.一个私有的 cookie 客户端既不能修改也不可查看.

构造函数以 key 来作为参数. 这是 Cookie 会话的私钥,如果更改此值,所有的会话都会丢失.

一般来说你创建一个 `SessionStorage` 中间件并使用指定后端实现来初始化它, 比如一个 `CookieSession`. 为了访问 session 的数据必须使用
`Session` 提取器. 该方法返回一个 [Session](https://docs.rs/actix-session/0.3.0/actix_session/struct.Session.html) 对象,
并允许我们访问或设置 session data.

```rust
use actix_session::{CookieSession, Session};
use actix_web::{web, App, Error, HttpResponse, HttpServer};

async fn index(session: Session) -> Result<HttpResponse, Error> {
    // 访问 Session数据
    if let Some(count) = session.get::<i32>("counter")? {
        session.set("counter", count + 1)?;
    } else {
        session.set("counter", 1)?;
    }

    Ok(HttpResponse::Ok().body(format!(
        "Count is {:?}!",
        session.get::<i32>("counter")?.unwrap()
    )))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .wrap(
                CookieSession::signed(&[0; 32]) // <- 基于Session中间件创建 cookie
                    .secure(false),
            )
            .service(web::resource("/").to(index))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```

## 错误处理

`ErrorHandlers` 中间件可以让我们为响应定制处理.

为指定的状态码你可以使用 `ErrorHandlers::handler()` 方法去注册一个错误处理函数. 你可以修改现在有响应,或者创建一个全新的. 错误处理函数
可以立即返回一个响应或者返回可以解析为响应的 future.

```rust
use actix_web::middleware::errhandlers::{ErrorHandlerResponse, ErrorHandlers};
use actix_web::{dev, http, HttpResponse, Result};

fn render_500<B>(mut res: dev::ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> {
    res.response_mut().headers_mut().insert(
        http::header::CONTENT_TYPE,
        http::HeaderValue::from_static("Error"),
    );
    Ok(ErrorHandlerResponse::Response(res))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    use actix_web::{web, App, HttpServer};

    HttpServer::new(|| {
        App::new()
            .wrap(
                ErrorHandlers::new()
                    .handler(http::StatusCode::INTERNAL_SERVER_ERROR, render_500),
            )
            .service(
                web::resource("/test")
                    .route(web::get().to(|| HttpResponse::Ok()))
                    .route(web::head().to(|| HttpResponse::MethodNotAllowed())),
            )
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```


================================================
FILE: doc/Requests.md
================================================
## 内容编码(Content Encoding)
Actix-web 能自动的解压缩 payloads (载荷). 支持如下几个解码器:
* Brotli
* Chunked
* Compress
* Gzip
* Deflate
* Identity
* Trailers
* EncodingExt

如果请求头中包含一个 `Content-Encoding` 头, 请求的payload会根据header中的值来解压缩. 不支持多重解码器. 比如: `Content-Encoding:br, gzip` .

## Json请求(Json Request)
对于Json body 的反序列化有一些可选项.

第一种选择是使用 _Json extractor_ (Json 提取器). 首先, 你要定义一个处理器函数将 `Json<T>` 作为一个参数来接收, 然后, 在处理器函数上
使用 `.to()` 方法来注册. 使用 `serde_json::Value` 作为类型 `T` , 可以接受任意有效的 json对象. 

```rust
use actix_web::{web, App, HttpServer, Result};
use serde::Deserialize;

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

/// 使用 serde 来提取Info 
async fn index(info: web::Json<Info>) -> Result<String> {
    Ok(format!("Welcome {}!", info.username))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| App::new().route("/", web::post().to(index)))
        .bind("127.0.0.1:8080")?
        .run()
        .await
}
```
你也可以手动的将payload导入内存中然后反序列化它.

在下面的示例中, 我们将反序列化一个 _MyObj_ struct. 我们必须首先导入request body 然后再反序列化json到一个Object对象中去.

```rust
use actix_web::{error, post, web, App, Error, HttpResponse};
use futures::StreamExt;
use serde::{Deserialize, Serialize};
use serde_json;

#[derive(Serialize, Deserialize)]
struct MyObj {
    name: String,
    number: i32,
}

const MAX_SIZE: usize = 262_144; // max payload size is 256k

#[post("/")]
async fn index_manual(mut payload: web::Payload) -> Result<HttpResponse, Error> {
    // payload是一个流式字节对象
    let mut body = web::BytesMut::new();
    while let Some(chunk) = payload.next().await {
        let chunk = chunk?;
        // 限制payload在内存中的最大 大小
        if (body.len() + chunk.len()) > MAX_SIZE {
            return Err(error::ErrorBadRequest("overflow"));
        }
        body.extend_from_slice(&chunk);
    }

    // body导入后现在我们使用 serde-json 来反序列化它
    let obj = serde_json::from_slice::<MyObj>(&body)?;
    Ok(HttpResponse::Ok().json(obj)) // <- 发送响应
}
```
两种选择的完整使用示例参考 [examples directory](https://github.com/actix/examples/tree/master/json/)

## 分块传输编码(Chunked transfer encoding)
Actix自动的解码 _chunked_ 编码. `web::Payload` 已经包含解码成字节流的方式. 如果请求负载(payload)是使用支持的编解码器(br, gzip, deflate)
其中之一来压缩, 那么会被作为字节流来解码.

## 多重body(Multipart body)
Actix-web 使用扩展包 `actix-multipart` 来支持多重流(stream).

完整的使用示例可以查看[examples directory](https://github.com/actix/examples/tree/master/multipart/)

# Urlencoded body
Actix-web 通过 `web::Form` 提取器为应用程序 _application/x-www-form-urlencoded_ 编码提供支持, 该提取器解析为反序列化实例. 这些实例必须从 serde 实现
`Deserialize` trait.

以下几种情况, _Urlencoded_ 未来可能解决错误.
* content type 不是 `applicaton/x-www-form-urlencoded`.
* transfer encoding 是 `chunked`.
* content-length 超过 256k.
* payload 终止错误.

```rust
use actix_web::{post, web, HttpResponse};
use serde::Deserialize;

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

#[post("/")]
async fn index(form: web::Form<FormData>) -> HttpResponse {
    HttpResponse::Ok().body(format!("username: {}", form.username))
}
```

## 流式请求(Streaming request)
_HttpRequest_ 是一个字节流对象. 它能用来读取请求 body的负载(payload).

在下面的示例中, 我们读取并分块打印 request payload.

```rust
use actix_web::{get, web, Error, HttpResponse};
use futures::StreamExt;

#[get("/")]
async fn index(mut body: web::Payload) -> Result<HttpResponse, Error> {
    let mut bytes = web::BytesMut::new();
    while let Some(item) = body.next().await {
        let item = item?;
        println!("Chunk: {:?}", &item);
        bytes.extend_from_slice(&item);
    }

    Ok(HttpResponse::Ok().finish())
}
```



================================================
FILE: doc/Responses.md
================================================
## 响应(Response)
一种类 builder 模式被使用来构造一个 `HttpResponse` 实例.  `HttpResponse` 提供了几个返回 `HttpResponseBuilder` 实例的方法,
此实例实现了一系列方便的方法用来构建响应.

查看文档 [documentation](https://docs.rs/actix-web/3/actix_web/dev/struct.HttpResponseBuilder.html) 获取类型描述.

方法 `.body`, `.finish`, 和 `.json` 完成响应的创建并返回构建好的 _HttpResponse_ 实例. 如果在同一构建器实例上多次调用这些方法,
构建器将会发生 panic(恐慌).

```rust
use actix_web::HttpResponse;

async fn index() -> HttpResponse {
    HttpResponse::Ok()
        .content_type("plain/text")
        .header("X-Hdr", "sample")
        .body("data")
}
```

## 内容编码(Content encoding)
Actix-web 能使用 [Compress middleware](https://docs.rs/actix-web/3/actix_web/middleware/struct.Compress.html) 自动的压缩payloads.
支持下面的编解码器:
* Brotli
* gzip
* Deflate
* Identity

```rust
use actix_web::{get, middleware, App, HttpResponse, HttpServer};

#[get("/")]
async fn index_br() -> HttpResponse {
    HttpResponse::Ok().body("data")
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .wrap(middleware::Compress::default())
            .service(index_br)
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```
根据中间件 `middleware::BodyEncoding` trait 的编码参数来压缩响应的payloads. 默认情况下 `ContentEncoding::Auto` 被使用. 如果使用
`ContentEncoding` 那么就会根据请求头中的 `Accept-Encoding` 来决定压缩.

`ContentEncoding::Identity` 可用来禁用压缩. 如果选择了其它方式的压缩, 那么该编解码器就会强制执行压缩.

例如对单个处理函数启用 `Brotli` 可以使用 `ContentEncoding::Br`.

```rust
use actix_web::{
    dev::BodyEncoding, get, http::ContentEncoding, middleware, App, HttpResponse, HttpServer,
};

#[get("/")]
async fn index_br() -> HttpResponse {
    HttpResponse::Ok()
        .encoding(ContentEncoding::Br)
        .body("data")
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .wrap(middleware::Compress::default())
            .service(index_br)
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```

或者在整个应用中配置:
```rust
use actix_web::{http::ContentEncoding, dev::BodyEncoding, HttpResponse};

async fn index_br() -> HttpResponse {
    HttpResponse::Ok().body("data")
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    use actix_web::{middleware, web, App, HttpServer};

    HttpServer::new(|| {
        App::new()
            .wrap(middleware::Compress::new(ContentEncoding::Br))
            .route("/", web::get().to(index_br))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```

我们通过设置content encoding 的值为 `Identity` 方式来禁用内容压缩.

```rust
use actix_web::{
    dev::BodyEncoding, get, http::ContentEncoding, middleware, App, HttpResponse, HttpServer,
};

#[get("/")]
async fn index() -> HttpResponse {
    HttpResponse::Ok()
        // 禁用压缩
        .encoding(ContentEncoding::Identity)
        .body("data")
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .wrap(middleware::Compress::default())
            .service(index)
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```

当我们处理已经存在压缩的body数据时(比如,当处理资产时), 通过手动设置 _header_ 中 `content-encoding` 的值为 `Identity` 的方式来避免压缩已经压缩过的数据.
```rust
use actix_web::{
    dev::BodyEncoding, get, http::ContentEncoding, middleware, App, HttpResponse, HttpServer,
};

static HELLO_WORLD: &[u8] = &[
    0x1f, 0x8b, 0x08, 0x00, 0xa2, 0x30, 0x10, 0x5c, 0x00, 0x03, 0xcb, 0x48, 0xcd, 0xc9, 0xc9, 0x57,
    0x28, 0xcf, 0x2f, 0xca, 0x49, 0xe1, 0x02, 0x00, 0x2d, 0x3b, 0x08, 0xaf, 0x0c, 0x00, 0x00, 0x00,
];

#[get("/")]
async fn index() -> HttpResponse {
    HttpResponse::Ok()
        .encoding(ContentEncoding::Identity)
        .header("content-encoding", "gzip")
        .body(HELLO_WORLD)
}
```

也可以在应用级别设置默认的内容编码, 默认情况下 `ContentEncoding::Auto` 被使用. 这意味着内容压缩是可以交涉的
(译者注: 换句话说,默认情况下是根据请求中的 Accept-encoding 来指定压缩方式的).

```rust
use actix_web::{get, http::ContentEncoding, middleware, App, HttpResponse, HttpServer};

#[get("/")]
async fn index() -> HttpResponse {
    HttpResponse::Ok().body("data")
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .wrap(middleware::Compress::new(ContentEncoding::Br)) // 这里就是设置应用级别的编码压缩方式.
            .service(index)
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```

## Json响应(Json Response)
`Json` 类型允许使用正确的Json格式数据进行响应. 只需要返回 `Json<T>` 类型, 其中`T`是序列化为Json格式的类型.
```rust
use actix_web::{get, web, HttpResponse, Result};
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
struct MyObj {
    name: String,
}

#[get("/a/{name}")]
async fn index(obj: web::Path<MyObj>) -> Result<HttpResponse> {
    Ok(HttpResponse::Ok().json(MyObj {
        name: obj.name.to_string(),
    }))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    use actix_web::{App, HttpServer};

    HttpServer::new(|| App::new().service(index))
        .bind("127.0.0.1:8080")?
        .run()
        .await
}
```





================================================
FILE: doc/Server.md
================================================
## Http服务器(The HTTP Server)
[HttpServer](https://docs.rs/actix-web/3/actix_web/struct.HttpServer.html) 负责HTTP请求的处理.

`HttpServer` 接收一个应用程序工厂作为一个参数,且应用程序工厂必须有 `Sync` + `Send` 边界. 会在多线程章节解释这一点.

使用 `bind()` 方法来绑定一个指定的Socket地址,它可以被多次调用. 使用 `bind_openssl()` 或者 `bind_rustls()` 方法绑定
ssl Socket地址. 使用 `HttpServer::run()` 方法来运行一个 Http 服务.

```rust
use actix_web::{web, App, HttpResponse, HttpServer};

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new().route("/", web::get().to(|| HttpResponse::Ok()))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```

`run()` 方法返回一个 `server` 类型的实例, server中的方法可以被用来管理HTTP服务器.
* pause() - 暂停接收进来的链接.
* resume() - 继续接收进来的链接.
* stop() - 停止接收进来的链接,且停止所有worker线程后退出.

下面的例子展示了如何在单独的线程中启动HTTP服务.

```rust
use actix_web::{web, App, HttpResponse, HttpServer, rt::System};
use std::sync::mpsc;
use std::thread;

#[actix_web::main]
async fn main() {
    let (tx, rx) = mpsc::channel();

    thread::spawn(move || {
        let sys = System::new("http-server");

        let srv = HttpServer::new(|| {
            App::new().route("/", web::get().to(|| HttpResponse::Ok()))
        })
        .bind("127.0.0.1:8080")?
        .shutdown_timeout(60) // <- 设置关机超时时间为60s.
        .run();

        let _ = tx.send(srv);
        sys.run()
    });

    let srv = rx.recv().unwrap();

    // 暂停接收新的链接
    srv.pause().await;
    // 继续接收新的链接
    srv.resume().await;
    // 停止服务
    srv.stop(true).await;
}
```

## 多线程(Multi-threading)
`HttpServer` 自动启动一些 Http Workers(工作线程), 它的默认值是系统cpu的逻辑个数. 这个值你可以通过 `HttpServer::workers()` 方法来自定义并覆盖.

```rust
use actix_web::{web, App, HttpResponse, HttpServer};

#[actix_web::main]
async fn main() {
    HttpServer::new(|| {
        App::new().route("/", web::get().to(|| HttpResponse::Ok()))
    })
    .workers(4); // <- 启动4个worker线程
}
```

一旦workers被创建,它们每个都接收一个单独的应用程序实例来处理请求.应用程序State不能在这些workers线程之间共享,且处理程序可以自由操作状态副本,而无需担心并发问题.

应用程序状态不需要 `Send` 或者 `Sync` , 但是应用程序工厂必须要是 `Send` + `Sync` (因为它需要在不同的线程中共享与传递).

为了在worker线程之间共享State, 可以使用 `Arc`. 引入共享与同步后,应该格外的小心,在许多情况下由于锁定共享状态而无意中造成了"性能成本".

在某些情况下,可以使用更加有效的锁策略来减少这种 "性能成本", 举个例子,可以使用读写锁 [read/write locks](https://doc.rust-lang.org/std/sync/struct.RwLock.html) 
来代替排它锁 [mutex](https://doc.rust-lang.org/std/sync/struct.Mutex.html) 来实现互斥性,但是性能最高的情况下,还是不要使用任何锁.

因为每一个worker线程是按顺序处理请求的,所以当处理程序阻塞当前线程时,会停止处理新的请求.

```rust
fn my_handler() -> impl Responder {
    std::thread::sleep(Duration::from_secs(5)); // <--  糟糕的实践方式,这样会导致当前worker线程停止处理新的请求.并挂起当前线程
    "response"
}
```

因此,任何长时间的或者非cpu绑定操作(比如:I/O,数据库操作等),都应该使用future或异步方法来处理. 异步处理程序由工作线程(worker)并发执行,
因此不会阻塞当前线程的执行.

例如下面的使用示例:
```rust
fn my_handler() -> impl Responder {
    tokio::time::delay_for(Duration::from_secs(5)).await; // 这种没问题,工作线程将继续处理其它请求.
    "response"
}
```
上面说的这种限制同样也存在于提取器(extractor)中. 当一个handler函数在接收一个实现了 `FromRequest` 的参数时, 并且这个实现
如果阻塞了当前线程,那么worker线程也会在运行时阻塞. 因此,在实现提取器时必须特别注意,在需要的时候要异步实现它们.

## SSL
有两种方式来实现ssl的server. 一个是 `rustls` 一个是 `openssl` . 在Cargo.toml文件中加入如下依赖:
```toml
[dependencies]
actix-web = { version = "3", features = ["openssl"] }
openssl = { version="0.10" }
```

```rust
use actix_web::{get, App, HttpRequest, HttpServer, Responder};
use openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};

#[get("/")]
async fn index(_req: HttpRequest) -> impl Responder {
    "Welcome!"
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // 导入 ssl keys
    // 为了测试创建自签名临时证书:
    // `openssl req -x509 -newkey rsa:4096 -nodes -keyout key.pem -out cert.pem -days 365 -subj '/CN=localhost'`
    let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
    builder
        .set_private_key_file("key.pem", SslFiletype::PEM)
        .unwrap();
    builder.set_certificate_chain_file("cert.pem").unwrap();

    HttpServer::new(|| App::new().service(index))
        .bind_openssl("127.0.0.1:8080", builder)?
        .run()
        .await
}
```

**注意:** HTTP2.0需要 [tls alpn](https://tools.ietf.org/html/rfc7301) 来支持, 目前仅仅只有 `openssl` 支持 `alpn`.
更多的示例可以参考 [examples/openssl](https://github.com/actix/examples/blob/master/openssl) .

为了创建生成key.pem与cert.pem,可以使用如下示例命令. **其它需要修改的地方请填写自己的主题**
```shell
openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -sha256 -subj "/C=CN/ST=Fujian/L=Xiamen/O=TVlinux/OU=Org/CN=muro.lxd"
```
要删除密码,然后复制 nopass.pem到 key.pem
```shell
openssl rsa -in key.pem -out nopass.pem
```

## 链接保持(Keep-Alive)
Actix 可以在keep-alive 链接上等待请求.

_keep alive_ 链接行为被server设置定义.
* 75, Some(75), KeepAlive::Timeout(75) - 开启keep alive 保活时间.
* None or KeepAlive::Disable - 关闭keep alive设置.
* KeepAlive::Tcp(75) - 使用 tcp socket SO_KEEPALIVE 设置选项.

```rust
use actix_web::{web, App, HttpResponse, HttpServer};

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let one = HttpServer::new(|| {
        App::new().route("/", web::get().to(|| HttpResponse::Ok()))
    })
    .keep_alive(75); // <- 设置keep alive时间为75秒.

    // let _two = HttpServer::new(|| {
    //     App::new().route("/", web::get().to(|| HttpResponse::Ok()))
    // })
    // .keep_alive(); // <- Use `SO_KEEPALIVE` socket option.

    let _three = HttpServer::new(|| {
        App::new().route("/", web::get().to(|| HttpResponse::Ok()))
    })
    .keep_alive(None); // <- 禁用 keep alive

    one.bind("127.0.0.1:8080")?.run().await
}
```

如果上面的第一个选项被选择,那么 _keep alive_ 状态将会根据响应的 _connection-type_ 类型来计算. 默认的 `HttpResponse::connection_type` 没有被定义
这种情况下会根据http的版本来默认是否开启keep alive.

_keep alive_ 在 HTTP/1.0是默认 **关闭** 的, 在 _HTTP/1.1_ 和 _HTTP/2.0_ 是默认**开启**的.

链接类型可以使用 `HttpResponseBuilder::connection_type()` 方法来改变.

```rust
 use actix_web::{http, HttpRequest, HttpResponse};
 async fn index(req: HttpRequest) -> HttpResponse {
    HttpResponse::Ok().connection_type(http::ConnectionType::Close) // 关闭链接
    .force_close() // 这种写法与上面那种写法二选一
    .finish()
}
```

## 优雅关机(Graceful shutdown)
`HttpServer` 支持优雅关机. 在接收到停机信号后,worker线程有一定的时间来完成请求. 超过时间后的所有worker都会被强制drop掉.
默认的shutdown 超时时间设置为30秒. 你也可以使用 `HttpServer::shutdown_timeout()` 方法来改变这个时间.

你可以使用服务器地址向服务器发送停止消息,并指定是否要正常关机, server的 `start()` 方法可以返回一个地址.

`HttpServer` 处理几种OS信号. _ctrl-c_ 在所有操作系统上都适用(表示优雅关机), 也可以在其它类unix系统上使用如下命令:
* SIGINT - 强制关闭worker
* SIGTERM - 优雅关闭worker
* SIGQUIT - 强制关闭worker

另外也可以使用 `HttpServer::disable_signals()` 方法来禁用信号处理.

================================================
FILE: doc/StaticFiles.md
================================================
## 个体文件(Individual file)
可以使用自定义路径模式和 `NameFile`来提供静态文件. 为了匹配路径尾端, 我们可以使用 `[.*]` 正则表达式.

```rust
use actix_files::NameFile;
use actix_web::{HttpRequest, Result};
use std::path::PathBuf;

async fn index(req: HttpRequest) -> Result<NamedFile> {
    let path: PathBuf = req.match_info().query("filename").parse().unwrap();
    Ok(NamedFile::open(path)?)
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    use actix_web::{web, App, HttpServer};

    HttpServer::new(|| App::new().route("/{filename:.*}", web::get().to(index)))
        .bind("127.0.0.1:8080")?
        .run()
        .await
}
```

## 目录(Directory)
提供来自指定目录或子目录的文件, 可以使用 `Files`. `Files` 必须使用 `App::service()` 方法来注册, 否而它不能被用在子目录处理上.

```rust
use actix_files as fs;
use actix_web::{App, HttpServer};

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

默认情况下子目录的文件清单是被禁用的. 尝试去加载目录列表将返回一个 _404 NOT FOUND_ 的响应. 为了启用文件清单功能, 要使用
[Files::show_files_listing()](https://docs.rs/actix-files/0.2/actix_files/struct.Files.html) 方法.

除了显示某个目录中文件的列表外, 还可以重定向到特定的index文件. 可以使用 [Files::index_file()](https://docs.rs/actix-files/0.2/actix_files/struct.Files.html#method.index_file) 来配置这个重定向.

## 配置(Configuration)
`NameFiles` 提供一系列的可选项:
* `set_content_disposition` - 函数用来将文件mime映射为 `Content-Disposition` 类型.
* `use_etag` - 指定是否计算ETag值并将其包含在headers中.
* `use_last_modified` - 指定是否将文件修改的时间戳添加在header的 `Last-Modified`中.

上面所有的方法都是可选的,并且提供了最佳的默认值,同时你也可以定制它们中的任何一个.
```rust
use actix_files as fs;
use actix_web::http::header::{ContentDisposition, DispositionType};
use actix_web::{get, App, Error, HttpRequest, HttpServer};

#[get("/{filename:.*}")]
async fn index(req: HttpRequest) -> Result<fs::NamedFile, Error> {
    let path: std::path::PathBuf = req.match_info().query("filename").parse().unwrap();
    let file = fs::NamedFile::open(path)?;
    Ok(file
        .use_last_modified(true)
        .set_content_disposition(ContentDisposition {
            disposition: DispositionType::Attachment,
            parameters: vec![],
        }))
}

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

该配置也可以用于目录:
```rust
use actix_files as fs;
use actix_web::{App, HttpServer};

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new().service(
            fs::Files::new("/static", ".")
                .show_files_listing()
                .use_last_modified(true),
        )
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```

================================================
FILE: doc/Testing.md
================================================
## 测试(Testing)
每一个应用程序都应该经过良好的测试. Actix-web 提供了执行单元与集成测试的工具.

## 单元测试(Unit Testing)
为了单元测试, actix_web提供了一个请求的builder类型. `TestRequest` 实现了类 builders 模式. 你可以使用 `to_http_requests()` 方法来生成
一个 `HttpRequest` 实例, 并且你可以用它来调用处理函数.

```rust
#[cfg(test)]
mod tests {
    use super::*;
    use actix_web::test;

    #[actix_rt::test]
    async fn test_index_ok() {
        let req = test::TestRequest::with_header("content-type", "text/plain").to_http_request();
        let resp = index(req).await;
        assert_eq!(resp.status(), http::StatusCode::OK);
    }

    #[actix_rt::test]
    async fn test_index_not_ok() {
        let req = test::TestRequest::default().to_http_request();
        let resp = index(req).await;
        assert_eq!(resp.status(), http::StatusCode::BAD_REQUEST);
    }
}
```

## 集成测试(Integration tests)
有几种测试应用程序的方法. Actix-web可用于在真实的HTTP服务器中使用特定的处理程序来运行程序. `TestRequest::get()`, `TestRequest::post()`,
可以被用作发送请求到测试服务器.

为了创建一个测试的 `Service`, 可以使用 `test::init_service` 方法来接受一个常规的 `App` 构建器.

更多信息查看 [API Documentation] (https://docs.rs/actix-web/3/actix_web/test/index.html).

```rust
#[cfg(test)]
mod tests {
    use super::*;
    use actix_web::{test, web, App};

    #[actix_rt::test]
    async fn test_index_get() {
        let mut app = test::init_service(App::new().route("/", web::get().to(index))).await;
        let req = test::TestRequest::with_header("content-type", "text/plain").to_request();
        let resp = test::call_service(&mut app, req).await;
        assert!(resp.status().is_success());
    }

    #[actix_rt::test]
    async fn test_index_post() {
        let mut app = test::init_service(App::new().route("/", web::get().to(index))).await;
        let req = test::TestRequest::post().uri("/").to_request();
        let resp = test::call_service(&mut app, req).await;
        assert!(resp.status().is_client_error());
    }
}
```

如果你需要更复杂的应用程序配置, 则测试应该与普通的应用程序创建非常类似. 比如说, 你可能需要初始化应用程序状态(State). 使用 `data` 方法
创建一个 `App` 并且附加状态, 这就像使用普通应用程序一样.

```rust
#[cfg(test)]
mod tests {
    use super::*;
    use actix_web::{test, web, App};

    #[actix_rt::test]
    async fn test_index_get() {
        let mut app = test::init_service(
            App::new()
                .data(AppState { count: 4 })
                .route("/", web::get().to(index)),
        ).await;
        let req = test::TestRequest::get().uri("/").to_request();
        let resp: AppState = test::read_response_json(&mut app, req).await;

        assert_eq!(resp.count, 4);
    }
}
```

## 流式响应测试(Stream response tests)
如果你需要测试流(Stream)的生成, 只要调用 `take_body()` 方法并转换结果 `ResponseBody` 到一个 _future_ 中并执行它, 比如当你在测试
[Server Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events) 时.

```rust
use std::task::Poll;
use bytes::Bytes;
use futures::stream::poll_fn;

use actix_web::http::{ContentEncoding, StatusCode};
use actix_web::{web, http, App, Error, HttpRequest, HttpResponse};

async fn sse(_req: HttpRequest) -> HttpResponse {
    let mut counter: usize = 5;

    // yields `data: N` where N in [5; 1]
    let server_events = poll_fn(move |_cx| -> Poll<Option<Result<Bytes, Error>>> {
        if counter == 0 {
            return Poll::Ready(None);
        }
        let payload = format!("data: {}\n\n", counter);
        counter -= 1;
        Poll::Ready(Some(Ok(Bytes::from(payload))))
    });

    HttpResponse::build(StatusCode::OK)
        .set_header(http::header::CONTENT_TYPE, "text/event-stream")
        .set_header(
            http::header::CONTENT_ENCODING,
            ContentEncoding::Identity.as_str(),
        )
        .streaming(server_events)
}

pub fn main() {
    App::new().route("/", web::get().to(sse));
}

#[cfg(test)]
mod tests {
    use super::*;

    use futures_util::stream::StreamExt;
    use futures_util::stream::TryStreamExt;

    use actix_web::{test, web, App};

    #[actix_rt::test]
    async fn test_stream() {
        let mut app = test::init_service(App::new().route("/", web::get().to(sse))).await;
        let req = test::TestRequest::get().to_request();

        let mut resp = test::call_service(&mut app, req).await;
        assert!(resp.status().is_success());

        // first chunk
        let (bytes, mut resp) = resp.take_body().into_future().await;
        assert_eq!(bytes.unwrap().unwrap(), Bytes::from_static(b"data: 5\n\n"));

        // second chunk
        let (bytes, mut resp) = resp.take_body().into_future().await;
        assert_eq!(bytes.unwrap().unwrap(), Bytes::from_static(b"data: 4\n\n"));

        // remaining part
        let bytes = test::load_stream(resp.take_body().into_stream()).await;
        assert_eq!(bytes.unwrap(), Bytes::from_static(b"data: 3\n\ndata: 2\n\ndata: 1\n\n"));
    }
}
```

================================================
FILE: doc/URLDispatch.md
================================================
## URL分发(URL Dispatch)
URL分发提供了一种使用简单模式匹配的方式去将URL映射到处理器函数代码上. 如果请求关联的路径信息被一个模式匹配, 那么一个特定的handler处理
函数对象会被激活.

一个请求处理器的功能是接收零个或多个能在请求中被提取的参数(ie, `impl FromRequest`) 且返回一个能被转换成HttpResponse的类型(ie, `impl HttpResponse`).
更多的信息参见[handler section](https://actix.rs/docs/handlers/).

## 资源配置(Resource configuration)
资源配置它是向应用中添加一个新资源的行为. 资源具有名称,该名称用于URL生成的标识符. 该名称也允许开发者向现有资源添加路由. 资源也有一种
模式, 这意味着可以匹配 _URL_ _PATH_ 中的一部分(比如格式与端口号后的一部分: /foo/bar in the URL http://localhost:8080/foo/bar?q=value).
它不匹配查询 _Query_ 的部分(?号后面的部分,比如: q=value in  http://localhost:8080/foo/bar?q=value)

使用 `App::route()` 方法提供了一个简单的方式注册路由. 这个方法添加单个路由到应用的路由表中去. 这个方法接收一个路径模式, HTTP方法和一个处理函数.
同一路径下`route()`方法可以被多次调用, 因此相同的资源路径可以注册多个路由.

```rust
use actix_web::{web, App, HttpResponse, HttpServer};

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

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .route("/", web::get().to(index))
            .route("/user", web::post().to(index))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```
虽然 _App::route()_ 提供了一个简单的方式来注册路由, 为了访问完整的资源配置,一个不同的方法可以使用. 它就是 `App::service()` 方法:添加
单个资源到应用路由表中去. 这个方法接收一个路径, guards, 和一个或多个routers.

```rust
use actix_web::{guard, web, App, HttpResponse};

fn index() -> HttpResponse {
    HttpResponse::Ok().body("Hello")
}

pub fn main() {
    App::new()
        .service(web::resource("/prefix").to(index))
        .service(
            web::resource("/user/{name}")
                .name("user_detail")
                .guard(guard::Header("content-type", "application/json"))
                .route(web::get().to(|| HttpResponse::Ok()))
                .route(web::put().to(|| HttpResponse::Ok())),
        );
}
```
如果一个资源不包含任何的路由或者没有任何能匹配上的路由,它将返回 _NOT FOUND_ HTTP响应(也就是404).

## 配置一个路由(Configuration a Route)
资源包含一组路由的集合. 每一个路由都依次有一组 `guards` 和 一个处理函数. 使用 `Resource::route()`方法创建一个新的路由,它返回一个新路由
实例的引用. 默认的情况下路由不包含任何的 guards, 因此所有的请求都可以被默认的处理器(HttpNotFound)处理.

应用程序传入请求是基于资源注册与路由注册期间定义的路由标准. 资源按 `Resource::route()` 注册的路由顺序来匹配所有的请求. 

一个路由可以包含任意数量 _guards_ 但仅仅只能有一个处理器函数.

```rust
#[actix_web::main]
fn main() -> std::io::Result<()> {
App::new().service(
    web::resource("/path").route(
        web::route()
            .guard(guard::Get())
            .guard(guard::Header("content-type", "text/plain"))
            .to(|| HttpResponse::Ok()),
    ),
)
}
```
在上面这个示例中, 如果GET请求中的header包含指定的 _Content-type_ 为 _text/plain_ 且路径为 `/path` `HttpResponse::Ok()`才会被返回.

如果资源没有任何匹配的路由,那么会返回 _NOT FOUNT_ 响应.

`ResourceHanlder::route()` 返回一个 `Route` 对象. Route使用类似builder模式来配置. 提供如下的配置方法: 
* `Route::guard()` - 注册一个新的守卫, 每个路由都能注册多个guards.
* `Route::method()` - 注册一个方法级守卫, 每个路由都能注册多个guards.
* `Route::to()` - 为某个路由注册一个处理函数. 仅能注册一个处理器函数. 通常处理器函数在最后的配置操作时注册.
* `Route::to_async()` - 注册一个异步处理函数. 仅能注册一个处理器函数. 通常处理器函数在最后的配置操作时注册.

## 路由匹配(Route matching)
路由配置的主要目的是针对一个URL路径模式去匹配(或者匹配)请求中的`path`. `path`代表被请求URL中的一部分.

_actix-web_ 做到这一点是非常简单的. 当一个请求进入到系统时, 对系统中存在的每一个资源配置声明,actix会根据声明的模式去检查请求中的路径.
这种检查按照 `App::service()` 方法声明的路径顺序进行. 如果找不到资源, 默认的资源就会作为匹配资源来使用.

当一个路由配置被声明时, 它可能包含路由的保护参数. 与路由声明关联的所有路由保护对于在检查期间用于给定请求路由的配置,都必须为ture
(译者注:换句话说, 路由上配置的所有guard,进来的请求都必须满足才能通过). 如果在检查期间注册在路由上的任意一个保护(guard)参数配置返回了`false`
那么当前路由就会被跳过,然后继续通过有序的路由集合进行匹配.

如果有任意一个路由被匹配上了, 那么路由匹配的过程就会停止与此路由相关联的处理函数就会被激活.如果没有一个路由被匹配上,就会得到一个 _NOT FOUND_ 的响应返回.

## 资源模式语法(Resource pattern syntax)
actix使用的模式匹配语言在匹配模式参数上是很简单的事.

在路由中使用模式可以使用斜杠开头. 如果模式不是以斜杠开头, 在匹配的时候会在前面加一个隐式的斜杠. 例如下面的模式是等效的:
```text
{foo}/bar/baz
```

和:

```text
/{foo}/bar/baz
```
上面变量替换的部分,{}标识符的形式指定, 这意味着 “直到下一个斜杠符前,可以接受任何的字符”, 并将其用作 `HttpRequest.match_info()`对象中的名称.

模式中的替换标记与正则表达式 `[^{}/]+` 相匹配.

匹配的信息是一个 `Params` 对象, 代表基于路由模式从URL中动态提取出来的部分. 它可以作为 `request.match_info` 信息来使用.
例如, 以下模式定义一个字段(foo)和两个标记(baz,and bar): 

```text
foo/{baz}/{bar}
```
上面的模式将匹配这些URL, 生成以下的匹配信息:

```text
foo/1/2         -> Params {'baz': '1', 'bar':'2'}
foo/abc/def     -> Params {'baz': 'abc', 'bar':'def'}
```
然而下面的模式不会被匹配:
```text
foo/1/2/         -> Not match(trailing slash) (不匹配最后面一个斜杠)
bar/abc/def      -> First segment literal mismatch (第一个字段就不匹配)
```
字面路径 _/foo/biz.html_ 将和上面的路由模式匹配,且匹配的结果 `Params{'name': 'biz' }`. 但是字面路径 _/foo/biz_ 不会被匹配,
是因为它由{name}.html表示的字段末尾不包含文字 _.html_ (因为它仅仅包含biz. 而不是biz.html).

为了要捕获两个分段, 可以使用两个替换标志符:
```text
foo/{name}.{ext}
```
字面路径 _/foo/biz.html_ 将会被上面的路由模式匹配, 并且匹配的结果将是 _Params {'name':'biz', 'ext':'html'}_ . 这种情况被匹配是因为
字面部分 _.(period)_ 在两个替换标记 _{name}_ 与 _{ext}_ 之间.

替换标记也可以使用正则表达式, 该正则表达式被用于确定路径段是否与标记匹配. 为了指定替换标记仅仅只匹配正则表达式定义的一组特定字符,你必须使用
稍微有扩展的替换标记语法. 在大括号内,替换标记名后必须跟一个冒号, 然后才是正则表达式. 与替换标记 `[^/]+` 相关联的是默认正则表达式匹配一个或
多个非斜杠的字符. 比如, 替换标记 _{foo}_ 可以更详细的写为 _{foo: [^/]+}_ 这种. 你可以将其更改为任意的正则表达式来匹配任意字符序列.比如: 
_{foo: \d+}_ 可以匹配 foo 后面的任意数字.

分段必须至少包含一个字符,这样才能匹配段替换标记. 例如,对于URL _/abc/_ :
* /abc/{foo} 不会匹配.
* /{foo} 将会匹配.

**注意**: 在匹配前, 将对路径(path)进行URL取消引号并将其解码为有效的unicode字符串, 且表示匹配路径段的值也将被URL取消引号.

因此,对于下面的模式:
```text
foo/{bar}
```
当它匹配下面这种URL时:
```text
http://example.com/foo/La%20Pe%C3%B1a
```
匹配字典看起来像下面这样(值是URL解码过的):
```text
Params {'bar': 'La Pe\xf1a'}
```
路径段中的文件字字符串会被代表解码后的值提供给actix. 如果你不想在模式中使用URL解码的值, 例如, 而不是这样:
```text
/Foo%20Bar/{baz}
```
你将使用以下内容:
```text
/Foo Bar/{baz}
```
有可能得到一种“尾部匹配”. 因此你必须使用正则表达式.
```text
foo/{bar}/{tail:.*}
```
上面的模式将和这些URL匹配, 生成如下匹配的信息:
```text
foo/1/2/                -> Params: { 'bar': '1', 'tail':'2' }
foo/abc/def/a/b/c       -> Params: { 'bar':u'abc', 'tail':'def/a/b/c' }
```

## 范围路由(Scoping Routes)
范围的界定可以帮助你组织共享路由的根路径. 你也可以嵌套范围(scopes).

假设你要组织 "Users" 的端点路径. 这样的路径可能包含:
* /users
* /users/show
* /users/show/{id}

这些路径作用域的布局如下:
```rust
#[get("/show")]
async fn show_users() -> HttpResponse {
    HttpResponse::Ok.body("Show Users")
}

#[get("/show/{id}")]
async fn user_detail(path: web::Path<(u32,)>) -> HttpResponse {
    HttpResponse::Ok.body(format!("User Detail: {}", path.into_inner().0))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(||{
        App::new().service(
            web::scope("/users")
            .service(show_users)
            .service(user_detail)
        )
    }).bind("127.0.0.1:8080")?
    .run().await
}
```
范围路径可以包含路径变量段来作为资源(译者注: 像上面示例的{id}). 与未限制范围的路径一致.

你可以从 `HttpRequest::match_info()` 方法中得到路径变量段值. `Path extractor` 还能提取范围级别的变量段.

## 匹配信息(Match information)
所有表示路径匹配段的值都可以在 `HttpRequest::match_info()` 中获取. 可以使用 `Path::get()` 方法来获取特定的值.

```rust
use actix_web::{get, App, HttpRequest, HttpServer, Result};

#[get("/a/{v1}/{v2}/")]
async fn index(req: HttpRequest) -> Result<String> {
    let v1: u8 = req.match_info().get("v1").unwrap().parse().unwrap();
    let v2: u8 = req.match_info().query("v2").parse().unwrap();
    let (v3, v4): (u8, u8) = req.match_info().load().unwrap();
    Ok(format!("Values {} {} {} {}", v1, v2, v3, v4))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| App::new().service(index))
        .bind("127.0.0.1:8080")?
        .run()
        .await
}
```
对于上面这个例子来说, 路径 '/a/1/2',分别对应v1和v2并被解析成"1"和"2".

可以从尾部路径参数创建一个 `PathBuf` . 返回的 `PathBuf` 按百分比解码. 如果一个分段等于 ".." 则跳过前一个段.

出于安全的目的, 如果一个分段满足下面任何一个条件, 则返回一个 `Err` , 表明已满足条件:
* 解码的分段以 `. (除了 ..), *` 任意一个开头的.
* 解码的分段以 `:`, `>`, `<` 任意一个结尾的.
* 解码的分段包含了任意的 `/`
* 在Windows上, 解码段包含任意的:  ‘'
* 百分比编码导致无效的UTF-8 

由于这些条件的存在, 根据请求路径参数解析出来的一个 `PathBuf` 可以安全的插入其中, 或用作没有其它检查的路径后缀.

```rust
use actix_web::{get, App, HttpRequest, HttpServer, Result};
use std::path::PathBuf;

#[get("/a/{tail:.*}")]
async fn index(req: HttpRequest) -> Result<String> {
    let path: PathBuf = req.match_info().query("tail").parse().unwrap();
    Ok(format!("Path {:?}", path))
}

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

## 路径信息提取器(Path information extractor)
Actix支持类型安全的路径信息提取功能. `Path` 提取信息, 目的地(转换后)的类型可以以几种不同的形式来定义. 一种简单的方式是一个 `tuple` 类型.
元组中的每一个元素必须对应模式路径中的一个元素. 比如: 你可以匹配一个路径模式 `/{id}/{username}` 为一个 `Path<(u32, String, String)>`
但是 `Path<(u32,String, String)>` 这种类型就会失败.

```rust
use actix_web::{get, web, App, HttpServer, Result};

#[get("/{username}/{id}/index.html")] // <- 定义路径参数
async fn index(info: web::Path<(String, u32)>) -> Result<String> {
    let info = info.into_inner();
    Ok(format!("Welcome {}! id: {}", info.0, info.1))
}

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

你也可以提取路径模式信息到一个结构体中. 在这种情况下结构体必须实现 **serde's** `Deserialize` trait.
```rust
use actix_web::{get, web, App, HttpServer, Result};
use serde::Deserialize;

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

// 使用serde提取路径信息
#[get("/{username}/index.html")] // <- 定义路径参数
async fn index(info: web::Path<Info>) -> Result<String> {
    Ok(format!("Welcome {}!", info.username))
}

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

为请求查询参数 [Query](https://docs.rs/actix-web/3/actix_web/web/struct.Query.html) 提供了类似的功能.

## 生成资源URL(Generating resource URLs)

使用 [HttpRequest.url_for()](https://docs.rs/actix-web/3/actix_web/struct.HttpRequest.html#method.url_for) 方法去生成基于
资源模式的URLs. 比如, 你配置了一个以"foo" 为名称的资源,并且模式是 “{a}/{b}/{c}”, 你可能会这样做:
```rust
use actix_web::{get, guard, http::header, HttpRequest, HttpResponse, Result};

#[get("/test/")]
async fn index(req: HttpRequest) -> Result<HttpResponse> {
    let url = req.url_for("foo", &["1", "2", "3"])?; // <- 为"foo"资源生成url

    Ok(HttpResponse::Found()
        .header(header::LOCATION, url.as_str())
        .finish())
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    use actix_web::{web, App, HttpServer};

    HttpServer::new(|| {
        App::new()
            .service(
                web::resource("/test/{a}/{b}/{c}")
                    .name("foo") // <- 设置资源名, 然后它可以被 'url_for'使用
                    .guard(guard::Get())
                    .to(|| HttpResponse::Ok()),
            )
            .service(index)
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```

这将返回类似 ` http://example.com/test/1/2/3` 的字符串(至少在当前协议与主机名下包含 http://example.com). `url_for()` 方法返回 `Url object` 
对象以变你可以修改这个url(添加查询参数,锚定等). `url_for()` 方法仅能在已经命名的资源时调用, 否则将返回错误.

## 外部资源(External resources)
有效的URL资源可以注册成外部资源.它们仅用于生成URL,而在请求时不考虑匹配.

```rust
use actix_web::{get, App, HttpRequest, HttpServer, Responder};

#[get("/")]
async fn index(req: HttpRequest) -> impl Responder {
    let url = req.url_for("youtube", &["oHg5SJYRHA0"]).unwrap();
    assert_eq!(url.as_str(), "https://youtube.com/watch/oHg5SJYRHA0");

    url.into_string()
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(index)
            .external_resource("youtube", "https://youtube.com/watch/{video_id}")
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```


## 路径正规化并重定向(Path normalization and redirection to slash-appended routes)

规范化意味着:
* 在路径上添加斜杠
* 用一个替换多个斜杠

这样的好处是处理器能够正确的解析路径(path)并返回. 如果全部启用, 规范化条件的顺序为 1) 合并, 2) 合并且追加 3). 如果路径至少满足这些条件中
的一个, 则它将重定向到新路径.
```rust
use actix_web::{middleware, HttpResponse};

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

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    use actix_web::{web, App, HttpServer};

    HttpServer::new(|| {
        App::new()
            .wrap(middleware::NormalizePath::default())
            .route("/resource/", web::to(index))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```
上面示例中的 `//resource///` 将会被重定向为 `/resource/` . 

在上面的示例中, 为所有方法(译者注: 指GET/POST/DELETE/PUT/HEAD等)注册了路径规范化处理函数,但是不能依赖此机制来重定向 _POST_ 请求.

带有斜杠的 _NOT FOUND_ 的重定向会将原POST请求转换成GET请求, 从而丢失原始请求POST中的所有数据.

可以仅仅针对GET请求注册规范化的路径:

```rust
use actix_web::{get, http::Method, middleware, web, App, HttpServer};

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .wrap(middleware::NormalizePath::default()) 
            .service(index)
            .default_service(web::route().method(Method::GET))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```

## 使用应用程序前缀来编写应用(Using an Application Prefix to Compose Applications)
`web::scope()` 方法允许你设置一个指定的应用程序范围. 此范围表示资源的前缀, 前缀能附加到资源配置添加的所有资源模式中. 它可以用在将一组
路由安装在与它包含的可被调用位置的不同地方, 同时还可以保持相同的资源名称(译者注: 很难理解, 你就当是 scope是一组路由资源的前缀就行了, 这样
做是好管理,资源路径清晰).

示例如下:
```rust
#[get("/show")]
async fn show_users() -> HttpResponse {
    HttpResponse::Ok().body("Show users")
}


#[get("/show/{id}")]
async fn user_detail(path: web::Path<(u32,)>) -> HttpResponse {
    HttpResponse::Ok().body(format!("User detail: {}", path.into_inner().0))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new().service(
            web::scope("/users")
                .service(show_users)
                .service(user_detail),
        )
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```
在上面的示例中, _show_users_ 路由的有效模式为 _/users/show_ 而不是 _/show_ 那是因为应用程序作用域(scope)会在该模式之前. 然后, 仅仅
当URL路径为 _/users/show_ 时路由才会被匹配, 并组当 `HttpRequest.url_for()` 函数被调用时, 它也会生成相同路径的URL.

## 自定义路由防护(Custom route guard)
你可以将路由防护(guard)看作是一个接收请求对象引用并返回ture或者false的简单函数. 一般来说一个防护它是实现了 `guard` trait的任何对象. 
Actix 提供了多个谓词, 你可以查看 [functions section](https://docs.rs/actix-web/3/actix_web/guard/index.html#functions) API 文档.

下面是一个简单的检查一个请求中是否包含指定 header 的防护示例:
```rust
use actix_web::{dev::RequestHead, guard::Guard, http, HttpResponse};

struct ContentTypeHeader;

// 实现Guard 并重写了check函数
impl Guard for ContentTypeHeader {
    fn check(&self, req: &RequestHead) -> bool {
        req.headers().contains_key(http::header::CONTENT_TYPE)
    }
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    use actix_web::{web, App, HttpServer};

    HttpServer::new(|| {
        App::new().route(
            "/",
            web::route()
                .guard(ContentTypeHeader) // 添加一个防护
                .to(|| HttpResponse::Ok()),
        )
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```
在上面的示例中, 仅当请求头中包含 _CONTENT-TYPE_ 时才会调用index 处理器.

防护(guard)不能够访问和修改请求对象, 但是它可以存一些额外的信息, 参考[request extensions](https://docs.rs/actix-web/3/actix_web/struct.HttpRequest.html#method.extensions)

## 修改防护(guard)值(Modifying guard values)
你可以通过将任意谓词的值包装在 `Not` 谓词中来反转其含义. 比如, 如果你想为除了 "GET" 以外的所有方法返回 "METHOD NOT ALLOWED" 响应,
可以使用如下示例方式操作:
```rust
use actix_web::{guard, web, App, HttpResponse, HttpServer};

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new().route(
            "/",
            web::route()
                .guard(guard::Not(guard::Get()))
                .to(|| HttpResponse::MethodNotAllowed()),
        )
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```
如果提供的guards能匹配 `Any` guard 表示接收一个防护清单
```
guard::Any(guard::Get()).or(guard::Post())  // 任意的Get Post都被接受
```
如果要使所有提供的 guards 能匹配, 可以使用 `All` guard.
```text
guard::All(guard::Get()).and(guard::Header("Content-Type","plain/text")) 
```
(译者注: 上面的表示所有的get且header中ContentType为 "plain/text" 的请求才能接受)

## 改变默认 **NOT FOUND** 响应(Changing the default NOT FOUND response)
如果路径模式不能在路由表中发现或者资源没有匹配的路由, 那么默认的资源就会被使用. 默认的响应是 _NOT FOUND_ . 可以使用 `App::default_service()`
方法来重写 _NOT FOUND_ 响应. 这个方法具有接受与 `App::service()` 方法的常规资源配置相同配置的功能.
```rust
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(web::resource("/").route(web::get().to(index)))
            .default_service(
                web::route()
                    .guard(guard::Not(guard::Get()))
                    .to(|| HttpResponse::MethodNotAllowed()),
            )
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}
```




================================================
FILE: doc/Webscokets.md
================================================
## Websockets
Actix-web使用 `actix-web-actors` 包来对WebSockets提供支持. 可以通过 [web::Payload](https://docs.rs/actix-web/3/actix_web/web/struct.Payload.html) 将请求的有效payload转换成 
[ws::Message](https://docs.rs/actix-web-actors/2/actix_web_actors/ws/enum.Message.html) 流, 然后使用组合器处理实时消息.
但是使用 _http actor_ 处理WebSocket通信更加简单.

下面是一个简单的 WebSocket 回声(echo) 示例:
```rust
use actix::{Actor, StreamHandler};
use actix_web::{web, App, Error, HttpRequest, HttpResponse, HttpServer};
use actix_web_actors::ws;

/// 定义 HTTP actor
struct MyWs;

impl Actor for MyWs {
    type Context = ws::WebsocketContext<Self>;
}

/// ws 消息处理器
impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for MyWs {
    fn handle(
        &mut self,
        msg: Result<ws::Message, ws::ProtocolError>,
        ctx: &mut Self::Context,
    ) {
        match msg {
            Ok(ws::Message::Ping(msg)) => ctx.pong(&msg),
            Ok(ws::Message::Text(text)) => ctx.text(text),
            Ok(ws::Message::Binary(bin)) => ctx.binary(bin),
            _ => (),
        }
    }
}

async fn index(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
    let resp = ws::start(MyWs {}, &req, stream);
    println!("{:?}", resp);
    resp
}

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

完整可用的 WebSocket echo 服务示例请查看 [examples directory](https://github.com/actix/examples/tree/master/websocket/)

[websocket-chat directory](https://github.com/actix/examples/tree/master/websocket-chat/) 这里面提供了一个聊天服务器示例,
可以通过websocket或TCP链接来实现聊天功能.

================================================
FILE: doc/WelcomeToActix.md
================================================
## 欢迎来到Actix(Welcome to Actix)
Actix Web 可以使你快速且自信的在Rust中开发Web服务, 而本指南将指导你如何使用它.

网站上的文档主要关注Actix Web 框架. 有关Actix的actor框架相关的信息, 请查看 [Actix book](https://actix.rs/book/actix) 
(或者低级别的 [actix API docs](https://docs.rs/actix) ). 否则,请转入 [起步与入门](GettingStarted.md) . 如果你了解自己的学习方式,
并且只需要特定的信息, 则可能你需要阅读 [actix-web API docs](https://docs.rs/actix-web) 文档.

================================================
FILE: doc/WhatIsActix.md
================================================
## Actix是相关包的生态系统(Actix is an ecosystem of crates)

&emsp;Actix 表示几种事务. 它基于Rust中功能强大的actor系统, 最开始是基于 `actix-web` 系统来构建的.这是你最可能使用的一点. `actix-web` 为你提供了功能强大且能快速开发的Web开发框架.

&emsp;我们一般称 `actix-web` 是一个小巧且实用的框架. 出于这些目的, 这是一个微框架. 如果你已经是一个Rust程序员,
那么你很快就能在这里找到家(译者注:有家的感觉?), 但即使你是由其它编程语言过来的,你也会发现 `actix-web` 上手非常容易.

&emsp;使用 `actix-web` 开发的应用将暴露一个本机可执行文件中包含的HTTP服务器. 同样,你也可以将它放在其它的HTTP服务
之后, 比如像nginx. 即使完全没有其它的HTTP服务器, `actix-web` 也足以提供 _HTTP/1_ 和 _HTTP/2_ 以及支持
TLS(HTTPS)服务. 这用来构建分发小型服务很有用.

&emsp;最重要的是: `actix-web` 是运行在Rust 1.42 及更高的stable release 版本之上.

================================================
FILE: src/bin/application.rs
================================================
use actix_web::{get, guard, web, App, HttpResponse, HttpServer, Responder};
use std::sync::Mutex;

/// ## 写一个应用
/// * actix-web 里面提供了一系列可以使用rust来构建web server的原语。它提供了路由,中间件,request预处理,response的后置处理等。
/// * 所有的actix-web servers都围绕App实例来构建. 它被用来注册路由资源来中间件. 它也存储同一个scope内所有处理程序之间共享的应用程序状态.
/// * 应用前缀总是包含一个 "/" 开头,如果提供的前缀没有包含斜杠,那么会默认自动的插入一个斜杠.
/// * 比如应用使用 /app 来限定,那么任何使用了路径为 /app, /app/ 或者 /app/test的请求都将被匹配,但是 /application这种path不会被匹配.
/// * 下面使用async main 函数来创建一个app 实例并注册请求处理器.
/// * 使用App::service 来处理使用路由宏,或者你也可以使用App::route来手功注册路由处理函数,声明一个path与方法.
/// * 最后使用HttpServer来启动服务,并处理incoming请求.
/// * 使用cargo run 运行,然后访问http://localhost:8080/ 或其它路由path 就可以看到结果.
/// * 下面这个例子使用 /app 前缀开头且以一个 index.html作用资源路径,因此完整的资源路径url就是 /app/index.html.
/// * 更多的信息,将会在URL Dispatch章节。
///
/// ## State
/// * 应用程序状态(State)被同一作用域(Scope)内的所有路由和资源共享。
/// * State 能被web::Data<T> 来访问,其中 T是 state的类型. State也能被中间件访问.
///
/// 让我们编写一个简单的应用程序并将应用程序名称存储在状态中,你可以在应用程序中注册多个State
///
/// ## 共享可变State
/// HttpServer接收一个应用程序工厂而不是一个应用程序实例,一个HttpServer 为每一个线程构造一个应用程序实例.
///
/// 因此必须多次构造应用程序数据,如果你想在两个不同的线程之间共享数据,一个可以共享的对象应用使用比如: Sync + Send
///
/// 内部 web::Data 使用 Arc. 因此为了避免创建两个 Arc, 我们应该在在使用App::app_data() 之前创建 好我们的数据。
/// 下面的例子中展示了应用中使用可变共享状态,首先我们定义state并创建处理器(handler).
///
/// ## 使用一个应用级Scope去组合应用
/// web::scope()方法允许你设置一个资源组前缀. 它表示所有资源类型(或者说是一组资源定位符)前缀配置。
/// 下面的 /app 就是这种使用方式,可以方便管理一组资源.
///
/// ## 应用防护和虚拟主机
/// 其实"防护"(guards)可以是说是actix-web为handler函数提供的一种安全配置.
/// 你可以将防护看成一个接收请求对象引用并返回ture或者false的简单函数. 可以说guard可以是实现了Guard trait的任何对象.
///
/// actix-web 提供了几种开箱即用的guards. 你可以在api文档中查找.
/// 其中一个guards就是 Header. 它可以被用在请求头信息的过滤.
///
/// ## 可配置
/// 为了简单与可重用,App与web::Scope两者都提供了configure方法. 此功能让配置的各个部分在不同的模块甚至不同的库(library)
/// 中移动时非常有用.
///
/// 其实这是一种拆分管理,一般来说可以提高代码重用,减少修改某个Scope组时可能带来的影响其它模块的错误.
/// 每一个ServiceConfig 都有它自己的 data, routers, 和 services

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // 外部声明一个counter
    let counter = web::Data::new(AppStateWithCounter {
        counter: Mutex::new(0),
    });
    HttpServer::new(move || {
        // 移动所有权
        App::new()
            // 在初始化的时候添加一个状态,并启动应用, 也就是说,这里设置的data,可以被同一Scope中的所有route共享到
            .data(AppState {
                app_name: String::from("Actix-web 3.0 demo"),
            })
            // 设置一个可变的State 在多个线程中共享, 适合在多个线程中需要修改的场景
            .app_data(counter.clone()) // 注册counter,为什么要用clone? 因为它需要在每个线程中共享
            .service(get_state)
            .configure(config) // 配置
            .configure(second_config)
            .service(
                // 所有以 /app 开头的path都将被匹配
                web::scope("/app")
                    // 为 /app 资源组添加一个Header guard Http Header 的Content-Type 必须为指定的类型
                    .guard(guard::Header("Content-Type", "application/html"))
                    // 这里会处理 /app/index.html的 get 请求
                    .route("/index.html", web::get().to(index))
                    // 同一个scope下再注册一个route
                    .route("/getAppInfo", web::get().to(app_info)),
            )
            .route("/", web::get().to(mutable_counter))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

async fn index() -> impl Responder {
    "hello actix-web 3.0"
}
async fn app_info() -> String {
    "This is app Info".to_string()
}

// 这个struct代表state
struct AppState {
    app_name: String,
}

#[get("/state/getState")]
async fn get_state(data: web::Data<AppState>) -> String {
    let app_name = &data.app_name;
    format!("Hello {}!", app_name) // 返回app name
}

// 可变共享计数器,可以在多个线程之间共享的state
struct AppStateWithCounter {
    counter: Mutex<i32>, // Mutex 排它锁,可以安全的在多个线程之间操作
}

async fn mutable_counter(data: web::Data<AppStateWithCounter>) -> String {
    let mut counter = data.counter.lock().unwrap(); // lock 会阻塞当前线程,直到它可用为止
    *counter += 1; // 解引用访问counter中的值,并 + 1
    format!("Request number : {}", counter) // 返回
}

/// 第一种配置function
fn config(cfg: &mut web::ServiceConfig) {
    cfg.service(
        web::resource("/t")
            .route(web::get().to(|| HttpResponse::Ok().body("This is oneConfig Response"))),
    );
}

/// 第二种配置function
fn second_config(cfg: &mut web::ServiceConfig) {
    cfg.service(
        web::scope("/secondScope")
            .guard(guard::Header("Content-Type", "application/text"))
            .route(
                "/test",
                web::get().to(|| HttpResponse::Ok().body("This is Second Config Response")),
            ),
    );
}


================================================
FILE: src/bin/errors_custom_error_response.rs
================================================
use actix_web::{
    dev::HttpResponseBuilder, error, get, http::header, http::StatusCode, middleware::Logger, App,
    HttpResponse, HttpServer, Result,
};
use derive_more::{Display, Error};
use log::debug;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // 设置环境变量参数
    std::env::set_var("RUST_LOG", "my_errors=debug,actix_web=debug"); // 这里需要将actix_web的日志级别设置为debug
    std::env::set_var("RUST_BACKTRACE", "1");
    env_logger::init();

    HttpServer::new(|| {
        App::new()
            // warp方法 注册一个中间件
            .wrap(Logger::default()) // 添加默认的日志设置
            .service(index)
            .service(user_error)
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

#[derive(Debug, Display, Error)]
enum MyError {
    #[display(fmt = "internal error")]
    InternalError,
    #[display(fmt = "bod request")]
    BadClientData,
    #[display(fmt = "timeout")]
    Timeout,
}

impl error::ResponseError for MyError {
    // 重写 error_response() 方法使用默认实现
    fn error_response(&self) -> HttpResponse {
        HttpResponseBuilder::new(self.status_code())
            .set_header(header::CONTENT_TYPE, "text/html; charset=utf-8")
            .body(self.to_string())
    }

    // 重写 status_code
    fn status_code(&self) -> StatusCode {
        match *self {
            MyError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,
            MyError::BadClientData => StatusCode::BAD_REQUEST,
            MyError::Timeout => StatusCode::GATEWAY_TIMEOUT,
        }
    }
}

#[get("/error")]
async fn index() -> Result<&'static str, MyError> {
    let err = MyError::BadClientData;
    debug!("{}", err);
    Err(err)
}

#[derive(Debug, Display, Error)]
enum UserError {
    #[display(fmt = "Validation error on field: {}", field)]
    Validation { field: String },
}

impl error::ResponseError for UserError {
    fn error_response(&self) -> HttpResponse {
        HttpResponseBuilder::new(self.status_code())
            .set_header(header::CONTENT_TYPE, "text/html; charset = utf-8")
            .body(self.to_string())
    }

    fn status_code(&self) -> StatusCode {
        match *self {
            UserError::Validation { .. } => StatusCode::BAD_REQUEST,
        }
    }
}

#[get("userError")]
async fn user_error() -> Result<&'static str, UserError> {
    let error = UserError::Validation {
        field: "username".to_string(),
    };
    debug!("{}", error);
    Err(error)
}


================================================
FILE: src/bin/extractors_application_state_arc.rs
================================================
use actix_web::{get, web, App, HttpServer, Responder};
use std::sync::atomic::{AtomicUsize, Ordering};

use std::sync::Arc;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let data = AppState {
        count: Arc::new(AtomicUsize::new(0)),
    };

    HttpServer::new(move || {
        App::new()
            .data(data.clone())
            .service(show_count)
            .service(add_one)
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

#[derive(Clone)]
struct AppState {
    // AtomicUsize: 一个可以安全的在多个线程是安全共享的整形
    count: Arc<AtomicUsize>,
}

#[get("/")]
async fn show_count(data: web::Data<AppState>) -> impl Responder {
    format!("count: {}", data.count.load(Ordering::Relaxed))
}

#[get("/add")]
async fn add_one(data: web::Data<AppState>) -> impl Responder {
    data.count.fetch_add(1, Ordering::Relaxed);

    format!("count: {}", data.count.load(Ordering::Relaxed))
}


================================================
FILE: src/bin/extractors_application_state_cell.rs
================================================
use actix_web::{web, App, HttpServer, Responder};
use std::cell::Cell;

/// 非线程安全版本的 应用程序状态使用示例
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // 初始化data
    let data = AppState {
        count: Cell::new(0),
    };
    HttpServer::new(move || {
        App::new()
            .data(data.clone())
            .route("/", web::get().to(show_count))
            .route("/add", web::get().to(add_one))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

#[derive(Clone)]
struct AppState {
    // Cell 可用在内部可变场景 内部提供get/set 来修改
    count: Cell<i32>,
}

async fn show_count(data: web::Data<AppState>) -> impl Responder {
    format!("count: {}", data.count.get())
}

async fn add_one(data: web::Data<AppState>) -> impl Responder {
    let count = data.count.get();
    data.count.set(count + 1);

    format!("count: {}", data.count.get())
}


================================================
FILE: src/bin/extractors_json.rs
================================================
use actix_web::web::Json;
use actix_web::{error, guard, web, App, HttpResponse, HttpServer, Result};
use serde::Deserialize;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        // 单独配置json
        let json_config = web::JsonConfig::default()
            .limit(4096) // 限制最大playload为 4kb
            .error_handler(|err, _req| {
                // 创建自定义错误响应
                error::InternalError::from_response(err, HttpResponse::Conflict().finish()).into()
            });
        App::new().service(
            web::scope("/json")
                .app_data(json_config) // 设置JsonConfig配置
                .guard(guard::Header("Content-Type", "application/json"))
                .route("/getInfo", web::get().to(get_info)),
        )
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

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

async fn get_info(info: Json<Info>) -> Result<String> {
    Ok(format!("Welcome {}!", info.username))
}


================================================
FILE: src/bin/extractors_type_safe_path.rs
================================================
use actix_web::{get, web, App, HttpRequest, HttpServer};
use serde::Deserialize;

/// ## 类型安全的信息提取器
/// actix-web 提供了一个灵活的类型安全的请求信息访问者,它被称为提取器(extractors)(实现了 impl FromRequest).
/// 默认下actix-web提供了几种extractors的实现.
///
/// 提取器可以被作为处理函数的参数访问. actix-web 每个处理函数(handler function)最多支持10个提取器. 它们作为参数的位置没有影响.
///
///## 路径(Path)
/// Path提供了能够从请求路径中提取信息的能力. 你可以从path中反序列化成任何变量.
///
/// 因此,注册一个/users/{user_id}/{friend}的路径, 你可以反序列化两个字段, user_id和 friend.
/// 这些字段可以被提取到一个 tuple(元组)中去, 比如: Path<u32, String> 或者是任何实现了 serde trait包中的 Deserialize
/// 的结构体(structure)
///
/// 也可以提取信息到一个指定的实现了serde trait反序列化的类型中去. 这种serde的使用方式与使用元组等效.
///
/// 另外你也可以使用 get 或者 query 方法从请求path中通过名称提取参数值
///
/// 请参见下面的示例:
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        // 注册一个/users/{user_id}/{friend} 的路由path
        // user_id 被反序列化为一个u32
        // friend 被反序列化为一个String
        // {} 占位符
        App::new()
            .route("/users/{user_id}/{friend}", web::get().to(get_user))
            .service(get_obj)
            .service(query)
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

/// 反序列化成一个元组
async fn get_user(web::Path((user_id, friend)): web::Path<(u32, String)>) -> String {
    format!("Welcome {}, user_id {}!", friend, user_id)
}

#[get("/getObj/{user_id}/{friend}")]
async fn get_obj(info: web::Path<User>) -> String {
    // 创建一个myInfo
    let my_info = User::new(18, "dsl".to_string());
    // 获取请求参数中的user信息
    println!("req user:{:?}", info);
    // 判断id是否相等
    if my_info.user_id == info.user_id {
        "Good! Equal user_id".to_string()
    } else {
        // 否则返回一个新的String
        format!(
            "this is new User [user_id:{}, friend:{}]",
            my_info.user_id, my_info.friend
        )
    }
}

#[get("/query/{age}/{username}")] // 定义请求路径参数
async fn query(req: HttpRequest) -> String {
    let age: u32 = req.match_info().get("age").unwrap().parse().unwrap();
    let username: String = req.match_info().query("username").parse().unwrap();
    format!("Hello {} your age:{}", username, age)
}

#[derive(Deserialize, Debug)]
struct User {
    user_id: u32,
    friend: String,
}

impl User {
    // create MyInfo
    fn new(user_id: u32, friend: String) -> Self {
        User { user_id, friend }
    }
}


================================================
FILE: src/bin/handlers_different_return_types.rs
================================================
use actix_web::{get, App, Either, Error, HttpResponse, HttpServer};
use rand::Rng;

/// ## 不同的返回类型(两种) Different Return Types(Either)
/// 有时候你需要在响应中返回两中不同的类型, 例如,您可以进行错误检查并返回错误,返回异步响应或需要两种不同类型的任何结果。
///
/// 对于这种情况, 你可以使用 Either类型, Either允许你组合两个不同类型的responder到一个单个类型中去.
///
/// 请看如下示例
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| App::new().service(index))
        .bind("127.0.0.1:8080")?
        .run()
        .await
}

type RegisterResult = Either<HttpResponse, Result<String, Error>>;

#[get("/")]
async fn index() -> RegisterResult {
    // 产生一个 0-9的随机整数
    let rand_num = rand::thread_rng().gen_range(0, 9);
    if rand_num < 5 {
        Either::A(HttpResponse::Ok().body("number less then 5"))
    } else {
        let res = format!("Great! This number is {}", rand_num);
        Either::B(Ok(res))
    }
}


================================================
FILE: src/bin/handlers_request_handlers.rs
================================================
use actix_web::{get, web, App, HttpRequest, HttpServer};
/// ## Request Handlers
/// 一个请求处理器,它是一个异步函数,可以接收零个或多个参数,而这些参数被实现了(ie, impl FromRequest)的请求所提取,
/// 并且返回一个被转换成 HttpResponse或者其实现(ie, impl Responder)的类型.
///
/// 请求处理发生在两个阶段:
///
/// 首先处理对象被调用,并返回一个实现了 Responder trait的任何对象.然后在返回的对象上调用 respond_to()方法,将其
/// 自身转换成一个 HttpResponse 或者 Error .
///
/// 默认情况下 actix-web 为 &‘static str , String 等提供了 Responder的标准实现.
///
/// 完整的实现清单可以参考 [Responder documentation](https://docs.rs/actix-web/3/actix_web/trait.Responder.html#foreign-impls)
///
/// 有效的 handler示例:
///
/// ```rust
/// async fn index(_req: HttpRequest) -> &'static str {
///     "Hello World"
/// }
/// async fn index_two(_req: HttpRequest) -> String {
///     "Hello world".to_string()
/// }
/// ```
/// 你也可以改变返回的签名为 impl Responder 它在要返回复杂类型时比较好用.
/// ```rust
/// async fn index(_req: HttpRequest) -> impl Responder {
///     Bytes::from_static(b"Hello world")
/// }
/// async fn index(_req: HttpRequest) -> impl Responder {
///     // ...
/// }
/// ```
#[actix_web::main()]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(index_two)
            .route("/", web::get().to(index))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

async fn index(_req: HttpRequest) -> &'static str {
    "Hello World"
}

#[get("/two")]
async fn index_two(_req: HttpRequest) -> String {
    "Hello world".to_string()
}


================================================
FILE: src/bin/handlers_response_with_custom_type.rs
================================================
use actix_web::{get, App, Error, HttpRequest, HttpResponse, HttpServer, Responder};
use futures::future::{ready, Ready};
use serde::Serialize;

/// ## Response with custom Type (返回自定义类型)
/// 为了直接从处理函数返回自定义类型的话, 需要这个类型实现 Responder trait.
///
/// 让我们创建一个自定义响应类型,它可以序列化为一个 application/json 响应.
/// 先在Cargo.toml文件中添加如下依赖项:
///
/// ```rust
/// serde = "1.0.116"
/// futures = "0.3.5"
/// serde_json = "1.0.57"
/// ```
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| App::new().service(index))
        .bind(SERVER_ADDRESS)?
        .run()
        .await
}

#[derive(Serialize)]
struct MyObj {
    name: &'static str,
}

//响应Content-Type
const CONTENT_TYPE: &str = "application/json";
const SERVER_ADDRESS: &str = "127.0.0.1:8080";

/// 自定义Responder实现
impl Responder for MyObj {
    type Error = Error;
    type Future = Ready<Result<HttpResponse, Error>>;

    fn respond_to(self, _req: &HttpRequest) -> Self::Future {
        // 先把self 序列化成一个json字符串
        let body = serde_json::to_string(&self).unwrap();

        // 创建响应并设置Content-Type
        ready(Ok(HttpResponse::Ok().content_type(CONTENT_TYPE).body(body)))
    }
}

#[get("/")]
async fn index() -> MyObj {
    MyObj { name: "user" }
}


================================================
FILE: src/bin/handlers_streaming_response_body.rs
================================================
use actix_web::{get, App, Error, HttpResponse, HttpServer};
use bytes::Bytes;
use futures::future::ok;
use futures::stream::once;

/// ## 流式响应Body (Streaming response body)
/// 响应也可以是异步的. 在下面的案例中, body 必须实现Steam trait(Stream<Item=Bytes, Error=Error>)
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| App::new().service(stream))
        .bind("127.0.0.1:8080")?
        .run()
        .await
}

#[get("/stream")]
async fn stream() -> HttpResponse {
    let body = once(ok::<_, Error>(Bytes::from_static(b"test")));

    HttpResponse::Ok()
        .content_type("application/json")
        .streaming(body)
}


================================================
FILE: src/bin/hello_world.rs
================================================
use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder};

/// ## Hello world 示例
///  * 1. Request 使用一个async 异步函数来处理,它接收0个或多个参数,这些参数能被Request提取,并且返回一个被
///  转换成HttpResponse类型的 trait.
///  * 2. 下面的异步处理函数,可以直接使用内置宏来附加路由信息。这允许你指定响应方法与资源path.
///  * 3. 另外你也可以不使用路由宏来注册handler函数,可以使用像v2版本的写法,例如下面的manual_hello函数.

#[get("/hello")]
async fn hello() -> impl Responder {
    HttpResponse::Ok().body("Hello world Rust!")
}

#[get("/test")]
async fn test() -> String {
    "Direct Response String".to_string()
}

#[get("/")]
async fn other() -> impl Responder {
    HttpResponse::Ok().body("Default Other Resp")
}

/// post echo server
#[post("/echo")]
async fn echo(req_body: String) -> impl Responder {
    HttpResponse::Ok().body(req_body)
}

/// 不使用声明式路由,手工构建响应fn 这种就是v2版本的写法
async fn manual_hello() -> impl Responder {
    HttpResponse::Ok().body("manual hello")
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // main 入口函数
    HttpServer::new(|| {
        App::new()
            // v3 版本的写法
            .service(hello)
            .service(test)
            .service(echo)
            .service(other)
            // v2 版本的写法
            .route("/hey", web::get().to(manual_hello))
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}


================================================
FILE: src/bin/middleware.rs
================================================
use actix_service::{Service, Transform};
use actix_web::{dev::ServiceRequest, dev::ServiceResponse, web, App, Error, HttpServer};

use futures::future::{ok, Ready};
use futures::{Future, FutureExt};

use std::pin::Pin;
use std::task::{Context, Poll};

/// 中间件使用示例所表达的意图是:
/// 在请求进来时且并处理函数处理之前,我们可以对请求做一些操作。
/// 在响应返回前,我们可以对响应做一些操作.
/// 这种方式给了用户更多可扩展,可定制化的可能.
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        let app = App::new().wrap_fn(|req, srv| {
            println!("Hi form start. You requested: {}", req.path());
            srv.call(req).map(|res| {
                println!("Hi form response");
                res
            })
        });
        app.route(
            "/middleware",
            web::get().to(|| async { "Hello Middleware" }),
        )
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

/// 在中间件处理过程器有两步.
/// 1. 中间件初始化, 下一个服务链中作为一个参数中间件工厂被调用.
/// 2. 中间件的调用方法被正常的请求调用.
pub struct SayHi;

///中间件工厂是来自 actix_service 包下的一个 `Transform` trait.
/// `S` - 下一个服务类型
/// `B` - 响应body类型
impl<S, B> Transform<S> for SayHi
where
    S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
    S::Future: 'static,
    B: 'static,
{
    type Request = ServiceRequest;
    type Response = ServiceResponse<B>;
    type Error = Error;
    type Transform = SayHiMiddleware<S>;
    type InitError = ();
    type Future = Ready<Result<Self::Transform, Self::InitError>>;

    fn new_transform(&self, service: S) -> Self::Future {
        ok(SayHiMiddleware { service })
    }
}

pub struct SayHiMiddleware<S> {
    service: S,
}

impl<S, B> Service for SayHiMiddleware<S>
where
    S: Service<Request = ServiceRequest, Response = ServiceResponse<B>, Error = Error>,
    S::Future: 'static,
    B: 'static,
{
    type Request = ServiceRequest;
    type Response = ServiceResponse<B>;
    type Error = Error;
    type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>>>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.service.poll_ready(cx)
    }

    fn call(&mut self, req: ServiceRequest) -> Self::Future {
        println!("Hi from start. You requested: {}", req.path());

        let fut = self.service.call(req);

        Box::pin(async move {
            let res = fut.await?;

            println!("Hi from response");
            Ok(res)
        })
    }
}


================================================
FILE: src/bin/middleware_error_handler.rs
================================================
use actix_web::middleware::errhandlers::{ErrorHandlerResponse, ErrorHandlers};
use actix_web::{dev, http, web, App, HttpResponse, HttpServer, Result};

/// 自己定义500错误响应
fn render_500<B>(mut res: dev::ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> {
    res.response_mut().headers_mut().insert(
        http::header::CONTENT_TYPE,
        http::HeaderValue::from_static("Error"),
    );
    Ok(ErrorHandlerResponse::Response(res))
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .wrap(ErrorHandlers::new().handler(http::StatusCode::INTERNAL_SERVER_ERROR, render_500))
            .service(
                web::resource("/test")
                    .route(web::get().to(|| HttpResponse::Ok().body("success")))
                    .route(web::head().to(|| HttpResponse::MethodNotAllowed())),
            )
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}


================================================
FILE: src/bin/middleware_logging.rs
================================================
use actix_web::{middleware, middleware::Logger, web, App, HttpResponse, HttpServer};
use env_logger::Env;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    // 初始化日志 info 级别
    env_logger::from_env(Env::default().default_filter_or("info")).init();

    HttpServer::new(|| {
        App::new()
            .wrap(Logger::default())
            // 设置日志格式
            .wrap(Logger::new("%a %{User-Agent}i"))
            // 包装一个中间件 设置默认响应header
            .wrap(middleware::DefaultHeaders::new().header("X-Version", "0.2"))
            .route(
                "/logging",
                web::get().to(|| HttpResponse::Ok().body("Hello logging")),
            )
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}


================================================
FILE: src/bin/middleware_session.rs
================================================
use actix_session::{CookieSession, Session};
use actix_web::{get, App, Error, HttpResponse, HttpServer};

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .wrap(
                CookieSession::signed(&[0; 32]) // 基于 Session 中间件创建一个cookie
                    .secure(false),
            )
            .service(index)
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

#[get("/cookie")]
async fn index(session: Session) -> Result<HttpResponse, Error> {
    // 访问  session 数据
    if let Some(count) = session.get::<i32>("counter")? {
        session.set("counter", count + 1)?;
    } else {
        session.set("counter", 1)?;
    }

    Ok(HttpResponse::Ok().body(format!(
        "Counter is : {}",
        session.get::<i32>("counter")?.unwrap() // get::<i32> 类型必须声明
    )))
}


================================================
FILE: src/bin/requests.rs
================================================
use actix_web::{error, post, web, App, Error, HttpResponse, HttpServer};
use futures::StreamExt;
use serde::{Deserialize, Serialize};
use serde_json;

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

#[derive(Deserialize, Serialize)]
struct MyObj {
    name: String,
    number: i32,
}

const MAX_SIZ: usize = 262144; // 256k 最大playload

/// 手动反序列化json 到一个 Object中去
#[post("/manual")]
async fn index_manual(mut payload: web::Payload) -> Result<HttpResponse, Error> {
    // payload 是一个字节流
    let mut body = web::BytesMut::new();
    while let Some(chunk) = payload.next().await {
        let chunk = chunk?;
        // 限制内存中 payload 最大大小
        if (body.len() + chunk.len()) > MAX_SIZ {
            return Err(error::ErrorBadRequest("overflow"));
        }
        body.extend_from_slice(&chunk);
    }

    // body 被导入了,现在我们使用 serde_json 反序列化它
    let obj = serde_json::from_slice::<MyObj>(&body)?;
    Ok(HttpResponse::Ok().json(obj)) // 返回响应
}


================================================
FILE: src/bin/responses.rs
================================================
use actix_web::dev::BodyEncoding;
use actix_web::{
    get, http::ContentEncoding, middleware, post, web, App, HttpResponse, HttpServer, Result,
};
use serde::{Deserialize, Serialize};

#[get("/default")]
async fn index_default() -> HttpResponse {
    HttpResponse::Ok()
        //.encoding(ContentEncoding::Identity) // 通过这种方式可以禁用内容压缩.
        .body("data")
}

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            //包装一个中间件
            .wrap(middleware::Compress::default()) // 使用默认压缩方式
            //.wrap(middleware::Compress::new(ContentEncoding::Br)) // 这种是全局指定响应的 编码方式,这样就不用在每一个handler函数中处理了.
            .service(index_default)
            .service(index_br)
            .service(index_json)
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

#[get("/br")]
async fn index_br() -> HttpResponse {
    HttpResponse::Ok()
        .encoding(ContentEncoding::Br) //通过 encoding() 方法显示指定响应的编码
        .body("data")
}

#[derive(Deserialize, Debug)]
struct MyJsonReq {
    name: String,
}

#[derive(Serialize)]
struct MyJsonResponse {
    result: String,
}

#[post("/json")]
async fn index_json(info: web::Json<MyJsonReq>) -> Result<HttpResponse> {
    // 打印一下info
    println!("request: {:?}", info);
    let name: String = info.into_inner().name;
    let resp = MyJsonResponse { result: name };
    Ok(HttpResponse::Ok().json(resp))
    // 注意使用Json提取器的时候 header中的 Content-Type 要为 application/json 这相当为handler 添加了个 guard
}


================================================
FILE: src/bin/server.rs
================================================
use actix_web::{rt::System, web, App, HttpResponse, HttpServer};
use std::sync::mpsc;
use std::thread;

/// ## HttpServer
/// HttpServer 负责处理Http请求.
///
/// HttpServer 接收一个应用程序工厂作为一个参数,且应用程序工厂必须有 Sync + Send 边界.
/// 会在多线程章节解释这一点.
///
/// 使用 bind() 方法来绑定一个指定的Socket地址,它可以被多次调用. 使用bind_openssl()或者bind_rustls()方法绑定
/// ssl Socket地址. 使用HttpServer::run()方法来运行一个Http 服务.
///
/// run()方法返回一个server类型的实例, server中的方法可以被用来管理HTTP服务器.
/// * pause() - 暂停接收进来的链接.
/// * resume() - 继续接收进来的链接.
/// * stop() - 停止接收进来的链接,且停止所有有worker线程后退出.
/// 下面的例子展示了如果在单独的线程中启动HTTP服务.
///
/// ## 多线程
/// HttpServer 自动启动一些 Http Workers(工作线程), 它的默认值是系统cpu的逻辑个数. 这个值你可以通过 HttpServer::workers()
/// 方法来自定义并覆盖.
///
/// 一旦workers被创建,它们每个都接收一个单独的应用程序实例来处理请求.应用程序State不能在这些workers线程之间共享,且处理程序可以自由操作状态副本,而无需担心并发问题.
///
/// 应用程序State不需要Send或者Sync,但是应用程序工厂必须要是Send + Sync (因为它需要在不同的线程中共享与传递).
///
/// 为了在worker 线程之间共享State, 可以使用Arc. 引入共享与同步后,应该格外的小心, 在许多情况下由于锁定共享状态而无意中造成了"性能成本".
///
/// 在某些情况下,可以使用更加有效的锁策略来减少这种"情能成本",举个例子,可以使用读写锁(read/write locks)来代替排它锁(mutex)来实现互斥性,
/// 但是性能最高的情况下,还是不要使用任何锁。
///
/// 因为每一个worker线程是安顺序处理请求的,所以处理程序阻塞当前线程,会并停止处理新的请求.
/// ```rust
/// fn my_handler() -> impl Responder {
///     std::thread::sleep(Duration::from_secs(5)); // 糟糕的实践方式,这样会导致当前worker线程停止处理新的请求.并挂起当前线程
///     "response"
/// }
/// ```
/// 因此,任何长时间的或者非cpu绑定操作(比如:I/O,数据库操作等),都应该使用future或异步方法来处理.
///
/// 异步处理程序由工作线程(worker)并发执行,因此不会阻塞当前线程的执行.例如下面的使用示例:
/// ```rust
/// fn my_handler() -> impl Responder {
///     tokio::time::delay_for(Duration::from_secs(5)).await; // 这种没问题,工作线程将继续处理其它请求.
/// }
/// ```
/// 上面说的这种限制同样也存在于提取器(extractor)中. 当一个handler函数在接收一个实现了 FromRequest 的参数时,并且这个实现
/// 如果阻塞了当前线程,那么worker线程也会在运行时阻塞.
///
/// 因此,在实现提取器时必须特别注意,在需要的时候要异步实现它们.
///
/// ## SSL
/// 有两种方式来实现ssl的server. 一个是rustls一个是openssl. 在Cargo.toml文件中加入如下依赖:
/// ``` rust
/// [dependencies]
/// actix-web = { version = "3", features = ["openssl"] }
/// openssl = {version = "0.10"}
/// ```
/// ```rust
/// #[get("/")]
/// async fn index(_req: HttpRequest) -> impl Responder {
///     "Welcome"
/// }
/// #[actix_web::main]
/// async fn main() -> std::io::Result<()> {
///     // 载入ssl key
///     // 为了测试可以创建自签名的证书
///     // 'openssl req -x509 -newkey ras:4096 -nodes -keyout key.pem -out cert.pem -days 365 -subj '/CN=localhost' '
///     let mut builder = SslAcceptor::mozilla_intermediate(SslMethod::tls()).unwrap();
///     builder
///         .set_private_key_file("key.pem", SslFiletype::PEM).unwrap();
///     builder.set_certificate_chain_file("cert.pem").unwrap();
///
///     HttpServer::new(||{
///         App::new().service(index)
///     }).bind_openssl("127.0.0.1:8080")?
///         .run().await
/// }
/// ```
/// **注意:** HTTP2.0需要[tls alpn](https://tools.ietf.org/html/rfc7301)支持,目前仅仅只有openssl有alpn支持.
/// 更多的示例可以参考[examples/openssl](https://github.com/actix/examples/blob/master/openssl)
///
/// 为了创建生成key.pem与cert.pem,可以使用如下示例命令. **其它需要修改的地方请填写自己的主题**
/// ```shell
/// openssl req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 -sha256 -subj "/C=CN/ST=Fujian/L=Xiamen/O=TVlinux/OU=Org/CN=muro.lxd"
/// ```
/// 要删除密码,然后复制 nopass.pem到 key.pem
/// ```shell
/// openssl rsa -in key.pem -out nopass.pem
/// ```
#[actix_web::main]
async fn main() {
    // 声明一个 多生产者单消费者的channel
    let (tx, rx) = mpsc::channel();
    thread::spawn(move || {
        let sys = System::new("http-server");
        let server = HttpServer::new(|| {
            App::new().service(
                web::scope("/app").route("/test", web::get().to(|| HttpResponse::Ok().body("Ok"))),
            )
        })
        .workers(4) // 自定义workers数量
        .bind("127.0.0.1:8080")?
        .shutdown_timeout(60) // 设置shutdown 时间为60秒
        .run();
        let _ = tx.send(server);
        println!("New Http Server Started op Port 8080");
        sys.run() // 会启动一个 event loop 服务直到 stop()方法被调用
    });
    let serv = rx.recv().unwrap();
    //暂停接收新的链接
    serv.pause().await;
    // 继续接收新的链接
    serv.resume().await;
    // 停止服务
    serv.stop(true).await;
    println!("Http Server has been Stopped");
}


================================================
FILE: src/bin/server_graceful_shutdown.rs
================================================
use actix_web::{get, App, HttpServer};

/// ## Graceful shutdown
/// HttpServer 支持优雅关机. 在接收到停机信号后,worker线程有一定的时间来完成请求. 超过时间后的所有worker都会被强制drop掉.
/// 默认的shutdown 超时时间设置为30秒. 你也可以使用 HttpServer::shutdown_timeout() 方法来改变这个时间.
///
/// 您可以使用服务器地址向服务器发送停止消息,并指定是否要正常关机, server的start()方法可以返回一个地址.
///
/// HttpServer 处理几种OS信号. ctrl-c 在所有操作系统上都适用(表示优雅关机), 也可以在其它类unix系统上使用如下命令:
/// * SIGINT - 强制关闭worker
/// * SIGTERM - 优雅关闭worker
/// * SIGQUIT - 强制关闭worker
/// 另外也可以使用 HttpServer::disable_signals()方法来禁用信号处理
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| App::new().service(index))
        .shutdown_timeout(60) // 设置关闭时间为60秒 超时后强制关闭worker
        .bind("127.0.0.1:8080")?
        .run()
        .await
}

#[get("/index")]
async fn index() -> String {
    "Rust Graceful Shutdown Demo".to_string()
}


================================================
FILE: src/bin/server_keepalive.rs
================================================
use actix_web::{web, App, HttpResponse, HttpServer};

/// ## Keep-Alive
/// Actix 可以在keep-alive 链接上等待请求.
///
/// keep alive 链接行为被 server设置定义.
/// * 75, Some(75), KeepAlive::Timeout(75) - 开启keep alive 保活时间
/// * None or KeepAlive::Disable - 关闭keep alive设置
/// * KeepAlive::Tcp(75) - 使用 tcp socket SO_KEEPALIVE 设置选项
/// 如果第一下选项被选择,那么keep alive 状态将会根据响应的connection-type类型来计算.默认的 HttpResponse::connection_type没有被定义
/// 这种情况下会根据 http的版本来默认是否开启keep alive
///
/// keep alive 在 HTTP/1.0是默认关闭的,在HTTP/1.1和HTTP/2.0是默认开启的.
///
/// 链接类型可以使用 HttpResponseBuilder::connection_type() 方法来改变.
/// ```rust
///  use actix_web::{http, HttpRequest, HttpResponse};
///  async fn index(req: HttpRequest) -> HttpResponse {
///     HttpResponse::Ok().connection_type(http::ConnectionType::Close) // 关闭链接
///     .force_close() // 这种写法与上面那种写法二选一
///     .finish()
/// }
/// ```
#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let one =
        HttpServer::new(|| App::new().route("/", web::get().to(|| HttpResponse::Ok().body("Ok"))))
            .keep_alive(75); // 设置keep alive 时间为75秒
                             // let _two = HttpServer::new(||{
                             //     App::new().route("/", web::get().to(|| HttpResponse::Ok().body("Ok")))
                             // }).keep_alive(); // 使用"SO_KEEPALIVE" socket 选项

    let _three =
        HttpServer::new(|| App::new().route("/", web::get().to(|| HttpResponse::Ok().body("Ok"))))
            .keep_alive(None); // 关闭keep alive

    one.bind("127.0.0.1:8080")?.run().await
}


================================================
FILE: src/bin/static_file.rs
================================================
use actix_files::NamedFile;
use actix_web::{get, App, HttpRequest, HttpServer, Result};
use std::path::PathBuf;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    HttpServer::new(|| {
        App::new()
            .service(get_file_by_name)
            // 使用.service()方法注册一个目录,并调用show_files_listing方法列出所有文件清单
            // show_files_listing() 返回的是一个 html格式 的response 且 response header中 content-type: text/html,
            .service(actix_files::Files::new("/getDir", "D://testDir").show_files_listing())
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

/// 通过一个指定的文件名获取一个文件
/// filename: 必须是一个文件的绝对路径比如在 windows上 D://a.txt
#[get("/getFile/{filename:.*}")] // 使用正则表达式 .* 表示任意扩展名的文件
async fn get_file_by_name(req: HttpRequest) -> Result<NamedFile> {
    // 得到一个PathBuf 它是一个mut 的path
    let path: PathBuf = req.match_info().query("filename").parse().unwrap();

    let file = NamedFile::open(path)?;
    Ok(file) // 返回文件的内容
}


================================================
FILE: src/bin/url_dispatch_scoping.rs
================================================
use actix_web::dev::RequestHead;
use actix_web::guard::Guard;
use actix_web::{get, http, middleware, web, App, HttpRequest, HttpResponse, HttpServer};
use serde::Deserialize;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    std::env::set_var("RUST_LOG", "my_errors=debug,actix_web=debug"); // 这里需要将actix_web的日志级别设置为debug
    std::env::set_var("RUST_BACKTRACE", "1");
    env_logger::init();

    HttpServer::new(|| {
        App::new()
            .service(
                web::scope("/users")
                    // 路径规范化默认情况下会,总是在path尾部添加一个 /
                    // 这意味着不管是使用声明式宏,还是手动.route()方式注册的 path都要以 / 结尾
                    // 否则将不能访问, 但Client 请求path /user/show/ 或 /user/show 都可以
                    // 甚至你的 path = /users//show/// 都能正常访问, 这就是NormalizePath的优点
                    .wrap(middleware::NormalizePath::default())
                    .guard(ContentTypeHeader)
                    // .guard(guard::Not(ContentTypeHeader))  // 这一句会反转guard 含义,表示所有带 Content-Type 的请求都不能过.
                    .service(show_users)
                    .service(user_detail)
                    .service(get_matches)
                    .service(get_username),
            )
            .service(external_resource)
            .external_resource("youtube", "https://youtube.com/watch/{video_id}")
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

#[get("/show/")]
async fn show_users() -> HttpResponse {
    HttpResponse::Ok().body("show_users")
}

#[get("/show/{id}/")]
async fn user_detail(path: web::Path<(u32,)>) -> HttpResponse {
    HttpResponse::Ok().body(format!("User detail: {}", path.into_inner().0))
}

#[get("/matcher/{v1}/{v2}/")]
async fn get_matches(req: HttpRequest) -> String {
    // 直接根据替换表达式名获取一个值
    let v1: u8 = req.match_info().get("v1").unwrap().parse().unwrap();

    let v2: String = req.match_info().query("v2").parse().unwrap();

    // 还可以使用 元组的模式匹配
    let (v3, v4): (u8, String) = req.match_info().load().unwrap();

    format!("Values {}, {}, {}, {}", v1, v2, v3, v4)
}

#[derive(Debug, Deserialize)]
struct Info {
    username: String,
}

#[get("/{username}/index.html/")]
async fn get_username(data: web::Path<Info>) -> String {
    format!("{}", data.username)
}

#[get("/external")]
async fn external_resource(req: HttpRequest) -> HttpResponse {
    let url = req.url_for("youtube", &["oHg5SJYRHA0"]).unwrap();

    assert_eq!(url.as_str(), "https://youtube.com/watch/oHg5SJYRHA0");

    // 手动修改一下header中的内容
    HttpResponse::Ok()
        .header("Content-Type", "text/plain")
        .body(url.into_string())
}

struct ContentTypeHeader;

impl Guard for ContentTypeHeader {
    fn check(&self, request: &RequestHead) -> bool {
        request.headers().contains_key(http::header::CONTENT_TYPE)
    }
}


================================================
FILE: src/bin/websocket_echo.rs
================================================
use actix::{Actor, StreamHandler};
use actix_web::{web, App, Error, HttpRequest, HttpResponse, HttpServer};
use actix_web_actors::ws;
use actix_web_actors::ws::{Message, ProtocolError};

/// 定义一个 HTTP actor
struct MyWs;

impl Actor for MyWs {
    type Context = ws::WebsocketContext<Self>;
}

impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for MyWs {
    fn handle(&mut self, msg: Result<Message, ProtocolError>, ctx: &mut Self::Context) {
        match msg {
            Ok(ws::Message::Ping(msg)) => ctx.pong(&msg),
            Ok(ws::Message::Text(text)) => ctx.text(text),
            Ok(ws::Message::Binary(bin)) => ctx.binary(bin),
            _ => (),
        }
    }
}

async fn index(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> {
    let resp = ws::start(MyWs {}, &req, stream);
    println!("{:?}", resp);
    resp
}

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


================================================
FILE: src/main.rs
================================================
fn main() {
    println!("Welcome to actix-web 3.0 demo");
}
Download .txt
gitextract_y59kkk7e/

├── .gitignore
├── Cargo.toml
├── LICENSE
├── README.md
├── doc/
│   ├── Application.md
│   ├── AutoReloading.md
│   ├── ConnectionLifecycle.md
│   ├── Databases.md
│   ├── Errors.md
│   ├── Extractors.md
│   ├── GettingStarted.md
│   ├── HTTP2.md
│   ├── HTTPServerInitialization.md
│   ├── Handlers.md
│   ├── Middleware.md
│   ├── Requests.md
│   ├── Responses.md
│   ├── Server.md
│   ├── StaticFiles.md
│   ├── Testing.md
│   ├── URLDispatch.md
│   ├── Webscokets.md
│   ├── WelcomeToActix.md
│   └── WhatIsActix.md
└── src/
    ├── bin/
    │   ├── application.rs
    │   ├── errors_custom_error_response.rs
    │   ├── extractors_application_state_arc.rs
    │   ├── extractors_application_state_cell.rs
    │   ├── extractors_json.rs
    │   ├── extractors_type_safe_path.rs
    │   ├── handlers_different_return_types.rs
    │   ├── handlers_request_handlers.rs
    │   ├── handlers_response_with_custom_type.rs
    │   ├── handlers_streaming_response_body.rs
    │   ├── hello_world.rs
    │   ├── middleware.rs
    │   ├── middleware_error_handler.rs
    │   ├── middleware_logging.rs
    │   ├── middleware_session.rs
    │   ├── requests.rs
    │   ├── responses.rs
    │   ├── server.rs
    │   ├── server_graceful_shutdown.rs
    │   ├── server_keepalive.rs
    │   ├── static_file.rs
    │   ├── url_dispatch_scoping.rs
    │   └── websocket_echo.rs
    └── main.rs
Download .txt
SYMBOL INDEX (109 symbols across 24 files)

FILE: src/bin/application.rs
  function main (line 49) | async fn main() -> std::io::Result<()> {
  function index (line 83) | async fn index() -> impl Responder {
  function app_info (line 86) | async fn app_info() -> String {
  type AppState (line 91) | struct AppState {
  function get_state (line 96) | async fn get_state(data: web::Data<AppState>) -> String {
  type AppStateWithCounter (line 102) | struct AppStateWithCounter {
  function mutable_counter (line 106) | async fn mutable_counter(data: web::Data<AppStateWithCounter>) -> String {
  function config (line 113) | fn config(cfg: &mut web::ServiceConfig) {
  function second_config (line 121) | fn second_config(cfg: &mut web::ServiceConfig) {

FILE: src/bin/errors_custom_error_response.rs
  function main (line 9) | async fn main() -> std::io::Result<()> {
  type MyError (line 28) | enum MyError {
    method error_response (line 39) | fn error_response(&self) -> HttpResponse {
    method status_code (line 46) | fn status_code(&self) -> StatusCode {
  function index (line 56) | async fn index() -> Result<&'static str, MyError> {
  type UserError (line 63) | enum UserError {
    method error_response (line 69) | fn error_response(&self) -> HttpResponse {
    method status_code (line 75) | fn status_code(&self) -> StatusCode {
  function user_error (line 83) | async fn user_error() -> Result<&'static str, UserError> {

FILE: src/bin/extractors_application_state_arc.rs
  function main (line 7) | async fn main() -> std::io::Result<()> {
  type AppState (line 24) | struct AppState {
  function show_count (line 30) | async fn show_count(data: web::Data<AppState>) -> impl Responder {
  function add_one (line 35) | async fn add_one(data: web::Data<AppState>) -> impl Responder {

FILE: src/bin/extractors_application_state_cell.rs
  function main (line 6) | async fn main() -> std::io::Result<()> {
  type AppState (line 23) | struct AppState {
  function show_count (line 28) | async fn show_count(data: web::Data<AppState>) -> impl Responder {
  function add_one (line 32) | async fn add_one(data: web::Data<AppState>) -> impl Responder {

FILE: src/bin/extractors_json.rs
  function main (line 6) | async fn main() -> std::io::Result<()> {
  type Info (line 28) | struct Info {
  function get_info (line 32) | async fn get_info(info: Json<Info>) -> Result<String> {

FILE: src/bin/extractors_type_safe_path.rs
  function main (line 23) | async fn main() -> std::io::Result<()> {
  function get_user (line 40) | async fn get_user(web::Path((user_id, friend)): web::Path<(u32, String)>...
  function get_obj (line 45) | async fn get_obj(info: web::Path<User>) -> String {
  function query (line 63) | async fn query(req: HttpRequest) -> String {
  type User (line 70) | struct User {
    method new (line 77) | fn new(user_id: u32, friend: String) -> Self {

FILE: src/bin/handlers_different_return_types.rs
  function main (line 11) | async fn main() -> std::io::Result<()> {
  type RegisterResult (line 18) | type RegisterResult = Either<HttpResponse, Result<String, Error>>;
  function index (line 21) | async fn index() -> RegisterResult {

FILE: src/bin/handlers_request_handlers.rs
  function main (line 35) | async fn main() -> std::io::Result<()> {
  function index (line 46) | async fn index(_req: HttpRequest) -> &'static str {
  function index_two (line 51) | async fn index_two(_req: HttpRequest) -> String {

FILE: src/bin/handlers_response_with_custom_type.rs
  function main (line 17) | async fn main() -> std::io::Result<()> {
  type MyObj (line 25) | struct MyObj {
  constant CONTENT_TYPE (line 30) | const CONTENT_TYPE: &str = "application/json";
  constant SERVER_ADDRESS (line 31) | const SERVER_ADDRESS: &str = "127.0.0.1:8080";
  type Error (line 35) | type Error = Error;
  type Future (line 36) | type Future = Ready<Result<HttpResponse, Error>>;
  method respond_to (line 38) | fn respond_to(self, _req: &HttpRequest) -> Self::Future {
  function index (line 48) | async fn index() -> MyObj {

FILE: src/bin/handlers_streaming_response_body.rs
  function main (line 9) | async fn main() -> std::io::Result<()> {
  function stream (line 17) | async fn stream() -> HttpResponse {

FILE: src/bin/hello_world.rs
  function hello (line 10) | async fn hello() -> impl Responder {
  function test (line 15) | async fn test() -> String {
  function other (line 20) | async fn other() -> impl Responder {
  function echo (line 26) | async fn echo(req_body: String) -> impl Responder {
  function manual_hello (line 31) | async fn manual_hello() -> impl Responder {
  function main (line 36) | async fn main() -> std::io::Result<()> {

FILE: src/bin/middleware.rs
  function main (line 15) | async fn main() -> std::io::Result<()> {
  type SayHi (line 37) | pub struct SayHi;
    type Request (line 48) | type Request = ServiceRequest;
    type Response (line 49) | type Response = ServiceResponse<B>;
    type Error (line 50) | type Error = Error;
    type Transform (line 51) | type Transform = SayHiMiddleware<S>;
    type InitError (line 52) | type InitError = ();
    type Future (line 53) | type Future = Ready<Result<Self::Transform, Self::InitError>>;
    method new_transform (line 55) | fn new_transform(&self, service: S) -> Self::Future {
  type SayHiMiddleware (line 60) | pub struct SayHiMiddleware<S> {
  type Request (line 70) | type Request = ServiceRequest;
  type Response (line 71) | type Response = ServiceResponse<B>;
  type Error (line 72) | type Error = Error;
  type Future (line 73) | type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::E...
  method poll_ready (line 75) | fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::...
  method call (line 79) | fn call(&mut self, req: ServiceRequest) -> Self::Future {

FILE: src/bin/middleware_error_handler.rs
  function render_500 (line 5) | fn render_500<B>(mut res: dev::ServiceResponse<B>) -> Result<ErrorHandle...
  function main (line 14) | async fn main() -> std::io::Result<()> {

FILE: src/bin/middleware_logging.rs
  function main (line 5) | async fn main() -> std::io::Result<()> {

FILE: src/bin/middleware_session.rs
  function main (line 5) | async fn main() -> std::io::Result<()> {
  function index (line 20) | async fn index(session: Session) -> Result<HttpResponse, Error> {

FILE: src/bin/requests.rs
  function main (line 7) | async fn main() -> std::io::Result<()> {
  type MyObj (line 15) | struct MyObj {
  constant MAX_SIZ (line 20) | const MAX_SIZ: usize = 262144;
  function index_manual (line 24) | async fn index_manual(mut payload: web::Payload) -> Result<HttpResponse,...

FILE: src/bin/responses.rs
  function index_default (line 8) | async fn index_default() -> HttpResponse {
  function main (line 15) | async fn main() -> std::io::Result<()> {
  function index_br (line 31) | async fn index_br() -> HttpResponse {
  type MyJsonReq (line 38) | struct MyJsonReq {
  type MyJsonResponse (line 43) | struct MyJsonResponse {
  function index_json (line 48) | async fn index_json(info: web::Json<MyJsonReq>) -> Result<HttpResponse> {

FILE: src/bin/server.rs
  function main (line 93) | async fn main() {

FILE: src/bin/server_graceful_shutdown.rs
  function main (line 15) | async fn main() -> std::io::Result<()> {
  function index (line 24) | async fn index() -> String {

FILE: src/bin/server_keepalive.rs
  function main (line 25) | async fn main() -> std::io::Result<()> {

FILE: src/bin/static_file.rs
  function main (line 6) | async fn main() -> std::io::Result<()> {
  function get_file_by_name (line 22) | async fn get_file_by_name(req: HttpRequest) -> Result<NamedFile> {

FILE: src/bin/url_dispatch_scoping.rs
  function main (line 7) | async fn main() -> std::io::Result<()> {
  function show_users (line 37) | async fn show_users() -> HttpResponse {
  function user_detail (line 42) | async fn user_detail(path: web::Path<(u32,)>) -> HttpResponse {
  function get_matches (line 47) | async fn get_matches(req: HttpRequest) -> String {
  type Info (line 60) | struct Info {
  function get_username (line 65) | async fn get_username(data: web::Path<Info>) -> String {
  function external_resource (line 70) | async fn external_resource(req: HttpRequest) -> HttpResponse {
  type ContentTypeHeader (line 81) | struct ContentTypeHeader;
  method check (line 84) | fn check(&self, request: &RequestHead) -> bool {

FILE: src/bin/websocket_echo.rs
  type MyWs (line 7) | struct MyWs;
    method handle (line 14) | fn handle(&mut self, msg: Result<Message, ProtocolError>, ctx: &mut Se...
  type Context (line 10) | type Context = ws::WebsocketContext<Self>;
  function index (line 24) | async fn index(req: HttpRequest, stream: web::Payload) -> Result<HttpRes...
  function main (line 31) | async fn main() -> std::io::Result<()> {

FILE: src/main.rs
  function main (line 1) | fn main() {
Condensed preview — 48 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (158K chars).
[
  {
    "path": ".gitignore",
    "chars": 22,
    "preview": "/target\n*.iml\n.idea\n\n\n"
  },
  {
    "path": "Cargo.toml",
    "chars": 628,
    "preview": "[package]\nname = \"actix-web3-CN-doc\"\nversion = \"0.1.0\"\nauthors = [\"dslchd <dslchd@qq.com>\"]\nedition = \"2018\"\n\n# See more"
  },
  {
    "path": "LICENSE",
    "chars": 1063,
    "preview": "MIT License\n\nCopyright (c) 2020 dslchd\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof "
  },
  {
    "path": "README.md",
    "chars": 1577,
    "preview": "# actix-web 3.0 中文文档\n\n## 1.说明\n基本上算是翻译了官文档,但是示例并不一定和官方的相同. 所有的示例代码都源自官方文档中的示例,但又不完全与之相同.\n\n算是一边学习一边理解写出来的demo代码且全部都能正常运行.\n"
  },
  {
    "path": "doc/Application.md",
    "chars": 5767,
    "preview": "## 编写一个应用程序(Writing an Application)\n`actix-web` 里面提供了一系列可以使用rust来构建web server的原语。它提供了路由,中间件,request预处理,response的后置处理等。\n\n"
  },
  {
    "path": "doc/AutoReloading.md",
    "chars": 356,
    "preview": "## 自动重载开发服务(Auto-Reloading Development Server)\n\n在开发的过程中,让**Cargo**在代码发生变化时自动编译是非常方便的. 可以使用 [cargo-watch](https://github."
  },
  {
    "path": "doc/ConnectionLifecycle.md",
    "chars": 919,
    "preview": "# 链接生命周期(Connection Lifecycle)\n\n## 架构总览(Architecture overview)\n在服务启动并监听所有socket链接后, `Accept` 和 `Worker` 两个主要的轮循是来处理从客户端传"
  },
  {
    "path": "doc/Databases.md",
    "chars": 2337,
    "preview": "## 异步选项(Async Options)\n我们(actix-web)提供了几个使用异步数据库适配器的示例工程:\n* SQLx: https://github.com/actix/examples/tree/master/sqlx_tod"
  },
  {
    "path": "doc/Errors.md",
    "chars": 6622,
    "preview": "## 错误(Errors)\nActix-web使用它自己的`actix_web::error::Error`类型和`actix_web::error:ResponseError` trait 来处理web处理函数中的错误.\n\n如果一个处理函"
  },
  {
    "path": "doc/Extractors.md",
    "chars": 7149,
    "preview": "## 类型安全的信息提取器(Type-safe information extractor)\n`actix-web` 提供了一个灵活的类型安全的请求信息访问者,它被称为提取器(extractors)(实现了 `impl FromReques"
  },
  {
    "path": "doc/GettingStarted.md",
    "chars": 1670,
    "preview": "## 安装Rust(Installing Rust)\n如果你还没有安装Rust, 我们建议你使用 `rustup` 来管理你的Rust安装. [official rust guide](https://doc.rust-lang.org/b"
  },
  {
    "path": "doc/HTTP2.md",
    "chars": 1381,
    "preview": "## HTTP2.0\n如果有可能 `actix-web` 会自动的将链接升级成 _HTTP/2_ .\n\n## Negotiation\n_HTTP/2_ 协议是基于TLS的且需要 [TLS ALPN](https://tools.ietf.o"
  },
  {
    "path": "doc/HTTPServerInitialization.md",
    "chars": 335,
    "preview": "## 架构总览(Architecture overview)\n下面的图表是 HttpServer 初始化过程, 它发生在如下代码处理过程中:\n\n```rust\n#[actix_web::main]\nasync fn main() -> st"
  },
  {
    "path": "doc/Handlers.md",
    "chars": 3023,
    "preview": "## 请求处理器(Request Handlers)\n一个请求处理器,它是一个异步函数,可以接收零个或多个参数,而这些参数被实现了(比如, [impl FromRequest](https://docs.rs/actix-web/3/act"
  },
  {
    "path": "doc/Middleware.md",
    "chars": 8189,
    "preview": "## 中间件(Middleware)\n\nActix-web 的中间件系统允许我们在请求/响应处理时添加一些其它的行为. 中间件可以(hook into)挂接到进入的请求处理过程中. 使我们能修改请求以及\n暂停请求处理来及早的返回响应.\n\n中"
  },
  {
    "path": "doc/Requests.md",
    "chars": 3478,
    "preview": "## 内容编码(Content Encoding)\nActix-web 能自动的解压缩 payloads (载荷). 支持如下几个解码器:\n* Brotli\n* Chunked\n* Compress\n* Gzip\n* Deflate\n* I"
  },
  {
    "path": "doc/Responses.md",
    "chars": 4921,
    "preview": "## 响应(Response)\n一种类 builder 模式被使用来构造一个 `HttpResponse` 实例.  `HttpResponse` 提供了几个返回 `HttpResponseBuilder` 实例的方法,\n此实例实现了一系列"
  },
  {
    "path": "doc/Server.md",
    "chars": 6286,
    "preview": "## Http服务器(The HTTP Server)\n[HttpServer](https://docs.rs/actix-web/3/actix_web/struct.HttpServer.html) 负责HTTP请求的处理.\n\n`Ht"
  },
  {
    "path": "doc/StaticFiles.md",
    "chars": 2748,
    "preview": "## 个体文件(Individual file)\n可以使用自定义路径模式和 `NameFile`来提供静态文件. 为了匹配路径尾端, 我们可以使用 `[.*]` 正则表达式.\n\n```rust\nuse actix_files::NameFi"
  },
  {
    "path": "doc/Testing.md",
    "chars": 4729,
    "preview": "## 测试(Testing)\n每一个应用程序都应该经过良好的测试. Actix-web 提供了执行单元与集成测试的工具.\n\n## 单元测试(Unit Testing)\n为了单元测试, actix_web提供了一个请求的builder类型. "
  },
  {
    "path": "doc/URLDispatch.md",
    "chars": 15857,
    "preview": "## URL分发(URL Dispatch)\nURL分发提供了一种使用简单模式匹配的方式去将URL映射到处理器函数代码上. 如果请求关联的路径信息被一个模式匹配, 那么一个特定的handler处理\n函数对象会被激活.\n\n一个请求处理器的功能"
  },
  {
    "path": "doc/Webscokets.md",
    "chars": 1658,
    "preview": "## Websockets\nActix-web使用 `actix-web-actors` 包来对WebSockets提供支持. 可以通过 [web::Payload](https://docs.rs/actix-web/3/actix_we"
  },
  {
    "path": "doc/WelcomeToActix.md",
    "chars": 348,
    "preview": "## 欢迎来到Actix(Welcome to Actix)\nActix Web 可以使你快速且自信的在Rust中开发Web服务, 而本指南将指导你如何使用它.\n\n网站上的文档主要关注Actix Web 框架. 有关Actix的actor框"
  },
  {
    "path": "doc/WhatIsActix.md",
    "chars": 553,
    "preview": "## Actix是相关包的生态系统(Actix is an ecosystem of crates)\n\n&emsp;Actix 表示几种事务. 它基于Rust中功能强大的actor系统, 最开始是基于 `actix-web` 系统来构建的."
  },
  {
    "path": "src/bin/application.rs",
    "chars": 4399,
    "preview": "use actix_web::{get, guard, web, App, HttpResponse, HttpServer, Responder};\nuse std::sync::Mutex;\n\n/// ## 写一个应用\n/// * ac"
  },
  {
    "path": "src/bin/errors_custom_error_response.rs",
    "chars": 2421,
    "preview": "use actix_web::{\n    dev::HttpResponseBuilder, error, get, http::header, http::StatusCode, middleware::Logger, App,\n    "
  },
  {
    "path": "src/bin/extractors_application_state_arc.rs",
    "chars": 912,
    "preview": "use actix_web::{get, web, App, HttpServer, Responder};\nuse std::sync::atomic::{AtomicUsize, Ordering};\n\nuse std::sync::A"
  },
  {
    "path": "src/bin/extractors_application_state_cell.rs",
    "chars": 863,
    "preview": "use actix_web::{web, App, HttpServer, Responder};\nuse std::cell::Cell;\n\n/// 非线程安全版本的 应用程序状态使用示例\n#[actix_web::main]\nasync"
  },
  {
    "path": "src/bin/extractors_json.rs",
    "chars": 1004,
    "preview": "use actix_web::web::Json;\nuse actix_web::{error, guard, web, App, HttpResponse, HttpServer, Result};\nuse serde::Deserial"
  },
  {
    "path": "src/bin/extractors_type_safe_path.rs",
    "chars": 2274,
    "preview": "use actix_web::{get, web, App, HttpRequest, HttpServer};\nuse serde::Deserialize;\n\n/// ## 类型安全的信息提取器\n/// actix-web 提供了一个灵"
  },
  {
    "path": "src/bin/handlers_different_return_types.rs",
    "chars": 853,
    "preview": "use actix_web::{get, App, Either, Error, HttpResponse, HttpServer};\nuse rand::Rng;\n\n/// ## 不同的返回类型(两种) Different Return "
  },
  {
    "path": "src/bin/handlers_request_handlers.rs",
    "chars": 1428,
    "preview": "use actix_web::{get, web, App, HttpRequest, HttpServer};\n/// ## Request Handlers\n/// 一个请求处理器,它是一个异步函数,可以接收零个或多个参数,而这些参数被"
  },
  {
    "path": "src/bin/handlers_response_with_custom_type.rs",
    "chars": 1225,
    "preview": "use actix_web::{get, App, Error, HttpRequest, HttpResponse, HttpServer, Responder};\nuse futures::future::{ready, Ready};"
  },
  {
    "path": "src/bin/handlers_streaming_response_body.rs",
    "chars": 641,
    "preview": "use actix_web::{get, App, Error, HttpResponse, HttpServer};\nuse bytes::Bytes;\nuse futures::future::ok;\nuse futures::stre"
  },
  {
    "path": "src/bin/hello_world.rs",
    "chars": 1273,
    "preview": "use actix_web::{get, post, web, App, HttpResponse, HttpServer, Responder};\n\n/// ## Hello world 示例\n///  * 1. Request 使用一个"
  },
  {
    "path": "src/bin/middleware.rs",
    "chars": 2432,
    "preview": "use actix_service::{Service, Transform};\nuse actix_web::{dev::ServiceRequest, dev::ServiceResponse, web, App, Error, Htt"
  },
  {
    "path": "src/bin/middleware_error_handler.rs",
    "chars": 942,
    "preview": "use actix_web::middleware::errhandlers::{ErrorHandlerResponse, ErrorHandlers};\nuse actix_web::{dev, http, web, App, Http"
  },
  {
    "path": "src/bin/middleware_logging.rs",
    "chars": 733,
    "preview": "use actix_web::{middleware, middleware::Logger, web, App, HttpResponse, HttpServer};\nuse env_logger::Env;\n\n#[actix_web::"
  },
  {
    "path": "src/bin/middleware_session.rs",
    "chars": 854,
    "preview": "use actix_session::{CookieSession, Session};\nuse actix_web::{get, App, Error, HttpResponse, HttpServer};\n\n#[actix_web::m"
  },
  {
    "path": "src/bin/requests.rs",
    "chars": 1083,
    "preview": "use actix_web::{error, post, web, App, Error, HttpResponse, HttpServer};\nuse futures::StreamExt;\nuse serde::{Deserialize"
  },
  {
    "path": "src/bin/responses.rs",
    "chars": 1494,
    "preview": "use actix_web::dev::BodyEncoding;\nuse actix_web::{\n    get, http::ContentEncoding, middleware, post, web, App, HttpRespo"
  },
  {
    "path": "src/bin/server.rs",
    "chars": 4045,
    "preview": "use actix_web::{rt::System, web, App, HttpResponse, HttpServer};\nuse std::sync::mpsc;\nuse std::thread;\n\n/// ## HttpServe"
  },
  {
    "path": "src/bin/server_graceful_shutdown.rs",
    "chars": 827,
    "preview": "use actix_web::{get, App, HttpServer};\n\n/// ## Graceful shutdown\n/// HttpServer 支持优雅关机. 在接收到停机信号后,worker线程有一定的时间来完成请求. 超"
  },
  {
    "path": "src/bin/server_keepalive.rs",
    "chars": 1535,
    "preview": "use actix_web::{web, App, HttpResponse, HttpServer};\n\n/// ## Keep-Alive\n/// Actix 可以在keep-alive 链接上等待请求.\n///\n/// keep al"
  },
  {
    "path": "src/bin/static_file.rs",
    "chars": 953,
    "preview": "use actix_files::NamedFile;\nuse actix_web::{get, App, HttpRequest, HttpServer, Result};\nuse std::path::PathBuf;\n\n#[actix"
  },
  {
    "path": "src/bin/url_dispatch_scoping.rs",
    "chars": 2763,
    "preview": "use actix_web::dev::RequestHead;\nuse actix_web::guard::Guard;\nuse actix_web::{get, http, middleware, web, App, HttpReque"
  },
  {
    "path": "src/bin/websocket_echo.rs",
    "chars": 1063,
    "preview": "use actix::{Actor, StreamHandler};\nuse actix_web::{web, App, Error, HttpRequest, HttpResponse, HttpServer};\nuse actix_we"
  },
  {
    "path": "src/main.rs",
    "chars": 61,
    "preview": "fn main() {\n    println!(\"Welcome to actix-web 3.0 demo\");\n}\n"
  }
]

About this extraction

This page contains the full source code of the dslchd/actix-web3-CN-doc GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 48 files (114.9 KB), approximately 41.4k tokens, and a symbol index with 109 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!