http-body-io
This is a very simple crate that implements IO traits for HTTP bodies. It is
intended to be used with tokio and the
http-body crate. This allows
you to use this crate with hyper and frameworks like
axum.
Example
This is an example with 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() {
let app = Router::new()
.route("/", get(root));
let listener = tokio::net::TcpListener::bind("0.0.0.0:3333").await.unwrap();
axum::serve(listener, app).await.unwrap();
}
async fn root() -> (StatusCode, Body) {
let buffer_size = 10.try_into().expect("10 is a valid buffer size");
let (body_writer, body_reader) = http_body_io::channel(buffer_size);
tokio::spawn(async move {
let mut body_writer = tokio::io::BufWriter::new(body_writer);
for _ in 0..100 {
body_writer.write_all(b"Hello World\n").await.unwrap();
}
body_writer.flush().await.unwrap();
});
(StatusCode::OK, Body::new(body_reader))
}