HTTP/2

http2.md
commit - 4d8d53cea59bca095ca5c02ef81f0b1791736855 - 2020.09.12

actix-web 可自动升级连接协议为 HTTP/2

协商

基于 TLS 的 HTTP/2 协议需要 TLS ALPN

当前,仅有 rust-openssl 提供了支持。

alpn 协商需要启用该功能。启用后,HttpServer 提供了 bind_openssl 方法。

[dependencies]
actix-web = { version = "{{< actix-version "actix-web" >}}", features = ["openssl"] }
openssl = { version = "0.10", features = ["v110"] }
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<()> {
    // load ssl keys
    // to create a self-signed temporary cert for testing:
    // `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
}

不支持升级到 rfc 章节 3.2 中描述的 HTTP/2.0 架构模式,但明文连接和 tls 连接都支持,需要在事先确定的情况下启动 HTTP/2。详见rfc 章节 3.4

查看 examples/tls 以获取具体示例。