| Crates.io | shared_http_body |
| lib.rs | shared_http_body |
| version | 0.1.6 |
| created_at | 2025-11-21 04:29:35.310118+00 |
| updated_at | 2025-12-13 02:49:30.396663+00 |
| description | A library for creating shareable HTTP bodies that can be cloned and consumed by multiple consumers |
| homepage | |
| repository | https://github.com/ankurmittal/shared-http-body-rs |
| max_upload_size | |
| id | 1943122 |
| size | 63,800 |
A Rust library for creating shareable HTTP bodies that can be cloned and consumed by multiple tasks.
shared_http_body provides SharedBody, which allows you to create an HTTP body that can be cloned and shared across multiple consumers. All clones share the same underlying body state, so clones created at the same time will see the same frames, while clones created after partial consumption will only see the remaining frames.
use shared_http_body::SharedBodyExt;
use http_body_util::{BodyExt, StreamBody};
use http_body::Frame;
use bytes::Bytes;
use futures_util::stream;
#[tokio::main]
async fn main() {
// Create a body from a stream of frames
let chunks = vec!["hello", "world"];
let stream = stream::iter(
chunks.into_iter()
.map(|s| Ok::<_, std::convert::Infallible>(Frame::data(Bytes::from(s))))
);
let body = StreamBody::new(stream);
let shared_body = body.into_shared();
// Clone the body for multiple consumers
let consumer1 = shared_body.clone();
let consumer2 = shared_body.clone();
// Both consumers will receive all frames
let (result1, result2) = tokio::join!(
consumer1.collect().map(|r| r.unwrap().to_bytes()),
consumer2.collect().map(|r| r.unwrap().to_bytes())
);
assert_eq!(result1, Bytes::from("helloworld"));
assert_eq!(result2, Bytes::from("helloworld"));
println!("Both consumers got: {:?}", result1);
}
Send + Sync - clones can be moved across threadsUnpin body: Compatible with most HTTP body typessize_hint() and is_end_stream() behavior.into_shared() on any body via SharedBodyExtCommon scenarios where cloning HTTP bodies is useful:
UnpinBody::Data) must implement CloneBody::Error) must implement CloneSend + SyncSharedBody uses futures_util::future::Shared internally to share the state of frame consumption across clones. Each frame is wrapped in a ClonableFrame that can clone both data frames and trailer frames. This allows multiple consumers to independently consume the same body without interference.
Licensed under the Apache License, Version 2.0.