#http-body #async-http #body #tokio #io #async

http-body-io

为 http-body 提供一个非常简单的 IO 包装器

3 个不稳定版本

0.2.1 2024年3月14日
0.2.0 2024年3月14日
0.1.1 2024年3月14日

#6 in #http-body

MIT 许可证

11KB
192 行代码(不含注释)

http-body-io

这是一个实现 HTTP 主体 IO 特性的非常简单的 crate。它旨在与 tokiohttp-body crate 一起使用。这允许您使用此 crate 与 hyper 和类似 axum 的框架一起使用。

示例

这是一个使用 axum 的示例。

[dependencies]
axum = "0.7.4"
http-body-io = "0.2"
tokio = { version = "1", features = ["full"] }
use axum::{body::Body, http::StatusCode, routing::get, Router};
use tokio::io::AsyncWriteExt;

#[tokio::main]
async fn main() {
    // build our application with a route
    let app = Router::new()
        // `GET /` goes to `root`
        .route("/", get(root));

    // run our app with hyper, listening globally on port 3333
    let listener = tokio::net::TcpListener::bind("0.0.0.0:3333").await.unwrap();
    axum::serve(listener, app).await.unwrap();
}

// basic handler that responds with a body reader
async fn root() -> (StatusCode, Body) {
    let buffer_size = 10.try_into().expect("10 is a valid buffer size");

    // We create a channel for the body with a buffer of 1
    // item.
    let (body_writer, body_reader) = http_body_io::channel(buffer_size);

    // Spawn a task to write the body
    tokio::spawn(async move {
        // Create a buffer for the writer, this is not necessary
        // but it can improve performance
        let mut body_writer = tokio::io::BufWriter::new(body_writer);

        // Write some data to the body 100 times
        for _ in 0..100 {
            body_writer.write_all(b"Hello World\n").await.unwrap();
        }

        // Flush the writer to finish the body
        body_writer.flush().await.unwrap();
    });

    // Return the body reader with a status code
    // The write operation will be finished in the background
    (StatusCode::OK, Body::new(body_reader))
}

依赖关系

~2.6–3.5MB
~57K SLoC