#http2 #h2 #server #api #wrapper #building #protocols

h2x

基于 h2 的轻量级包装,提供了构建 HTTP/2 服务器的便捷 API

6 个版本 (重大更新)

0.5.0 2024 年 6 月 5 日
0.4.0 2023 年 8 月 26 日
0.3.1 2023 年 6 月 6 日
0.2.0 2023 年 6 月 3 日
0.1.0 2023 年 6 月 1 日

网络编程 中排名第 1549

MIT 许可证

22KB
370

h2x

h2x 提供了对 h2 crate 的包装,为使用 HTTP/2 协议提供了额外的功能和实用函数。

它旨在简化 h2 crate 的使用,并提供一个更便于构建 HTTP/2 服务器的 API。

目标

  • 管理 TCP 连接
  • TLS

如果您只需要 HTTP/2 服务器且不能牺牲任何开销,这个库适合您。

入门指南

要在 Rust 项目中使用 h2x,请在您的 Cargo.toml 文件中将它作为依赖项添加

[dependencies]
h2x = "0.4"

示例

您可以使用以下命令运行此示例:cargo run --example hello_world

use h2x::*;
use http::{Method, StatusCode};
use std::{io, net::SocketAddr};


#[derive(Clone)]
struct Service {
    addr: SocketAddr,
}

impl Incoming for Service {
    async fn stream(self, req: Request, mut res: Response) {
        println!("From: {} at {}", self.addr, req.uri.path());
        let _ = match (&req.method, req.uri.path()) {
            (&Method::GET, "/") => res.write("<H1>Hello, World</H1>").await,
            _ => {
                res.status = StatusCode::NOT_FOUND;
                res.write(format!("{req:#?}\n")).await
            }
        };
    }

    async fn close(self) {
        println!("[{}] CONNECTION CLOSE", self.addr)
    }
}

#[tokio::main]
async fn main() -> io::Result<()> {
    let conf = Server::config("examples/key.pem", "examples/cert.pem")?;
    let server = Server::bind("127.0.0.1:4433", conf).await?;

    println!("Goto: https://{}", server.local_addr()?);

    loop {
        if let Ok((conn, addr)) = server.accept().await {
            println!("[{}] NEW CONNECTION", addr);
            conn.incoming(Service { addr });
        }
    }
}

更多示例,请参阅 ./examples 目录。

依赖项

~12–21MB
~377K SLoC