pub struct HttpBodyBuilder { /* private fields */ }Expand description
Builder for creating optimized HTTP bodies.
This builder optimizes memory usage and performance for HTTP bodies by providing:
- Memory pooling for better performance
- Runtime-specific optimizations
- Easier testing with the
test-utilfeature
§Examples
// Create different body types
let text_body: HttpBody = builder.text("Hello world");
let empty_body: HttpBody = builder.empty();
let binary_body: HttpBody = builder.slice(&[1, 2, 3, 4]);§Testing
With the test-util feature enabled, you can create a test instance using HttpBodyBuilder::new_fake().
Implementations§
Source§impl HttpBodyBuilder
impl HttpBodyBuilder
Sourcepub fn new_fake() -> HttpBodyBuilder
pub fn new_fake() -> HttpBodyBuilder
Creates a test-friendly HttpBodyBuilder instance.
Useful for unit tests. Available with the test-util feature, this allows creating and
working with HTTP bodies without any real network or server setup.
Uses a frozen clock, so body data receive timeouts will never fire.
§Examples
let builder = HttpBodyBuilder::new_fake();
let text_body = builder.text("Test content");Sourcepub fn new(memory: GlobalPool, clock: &Clock) -> HttpBodyBuilder
pub fn new(memory: GlobalPool, clock: &Clock) -> HttpBodyBuilder
Creates a new instance of HttpBodyBuilder.
This method uses a per-thread memory pool from GlobalPool.
Sourcepub fn with_custom_memory(
memory: impl MemoryShared,
clock: &Clock,
) -> HttpBodyBuilder
pub fn with_custom_memory( memory: impl MemoryShared, clock: &Clock, ) -> HttpBodyBuilder
Creates a new instance of HttpBodyBuilder with custom memory.
When using this method, the memory is shared across all threads as opposed
to the global per-thread memory used by HttpBodyBuilder::new.
Sourcepub fn with_options(self, options: HttpBodyOptions) -> HttpBodyBuilder
pub fn with_options(self, options: HttpBodyOptions) -> HttpBodyBuilder
Sets default HttpBodyOptions for all bodies created by this builder.
Per-call options passed to body or stream are
merged on top: the per-call value wins when both sides set the same field.
Sourcepub fn body<B>(&self, body: B, options: &HttpBodyOptions) -> HttpBody
pub fn body<B>(&self, body: B, options: &HttpBodyOptions) -> HttpBody
Creates an HttpBody from any body implementation.
Use this to integrate custom types that implement http_body::Body with the
HttpBody system. Useful for third-party libraries or your own custom body
implementations.
When options contains a timeout, the body is wrapped with an idle timeout that limits
how long the body may go without yielding a frame.
§Examples
// Your custom body type
struct CustomBody(Vec<u8>);
impl Body for CustomBody {
type Data = BytesView;
type Error = HttpError;
fn poll_frame(
self: Pin<&mut Self>,
_cx: &mut Context<'_>,
) -> Poll<Option<Result<http_body::Frame<Self::Data>, Self::Error>>> {
// Implementation details...
Poll::Ready(None)
}
}
// Create HttpBody from your custom body
let custom_body = CustomBody(vec![1, 2, 3, 4]);
let body = builder.body(custom_body, &HttpBodyOptions::default());Sourcepub fn stream<S>(&self, stream: S, options: &HttpBodyOptions) -> HttpBody
pub fn stream<S>(&self, stream: S, options: &HttpBodyOptions) -> HttpBody
Creates a body from a stream of byte chunks.
Accepts a Stream of BytesView chunks and creates a streaming
body from them.
When options contains a timeout, the stream is wrapped with an idle timeout that limits
how long the body may go without yielding a frame.
§Examples
let chunks = vec![
Ok(BytesView::copied_from_slice(b"hello ", &builder)),
Ok(BytesView::copied_from_slice(b"world", &builder)),
];
let body = builder.stream(futures::stream::iter(chunks), &HttpBodyOptions::default());
assert_eq!(body.content_length(), None); // unknown length for streams
Sourcepub fn text(&self, str: impl AsRef<str>) -> HttpBody
pub fn text(&self, str: impl AsRef<str>) -> HttpBody
Creates a body from text.
Works with both string literals and String types.
§Examples
let body1 = builder.text("Hello, world!"); // From &str
let body2 = builder.text(String::from("Hello, world!")); // From String
assert_eq!(body1.content_length(), body2.content_length());Sourcepub fn slice(&self, data: impl AsRef<[u8]>) -> HttpBody
pub fn slice(&self, data: impl AsRef<[u8]>) -> HttpBody
Creates a body from a slice of bytes.
Use this when you have a single slice of raw bytes that needs to be sent in a request or response.
§Performance
This will copy the contents of the byte slice. For more efficiency, you should consider
using bytes().
§Examples
// "Hello" in ASCII
let data = [0x48, 0x65, 0x6C, 0x6C, 0x6F];
let body = builder.slice(&data);
assert_eq!(body.content_length(), Some(5));Sourcepub fn bytes(&self, b: impl Into<BytesView>) -> HttpBody
pub fn bytes(&self, b: impl Into<BytesView>) -> HttpBody
Creates a body from an existing BytesView.
Use this when you already have a BytesView and want to use it as an HTTP body.
§Performance
This method does not copy the contents of the BytesView,
providing greater efficiency compared to slice().
§Examples
// Create a body from existing bytes of data
let body = builder.bytes(BytesView::new());
assert_eq!(body.content_length(), Some(0));Sourcepub fn empty(&self) -> HttpBody
pub fn empty(&self) -> HttpBody
Creates an empty body (zero bytes).
Use this for HTTP methods that don’t need a body like GET or HEAD requests, or for responses that only need status codes or headers.
Sourcepub fn json<T>(&self, data: &T) -> Result<HttpBody, JsonError>where
T: Serialize,
pub fn json<T>(&self, data: &T) -> Result<HttpBody, JsonError>where
T: Serialize,
Creates a body from a JSON-serializable value.
Automatically handles serialization and creates an HTTP body ready to send.
Available with the json feature.
§Errors
Returns an error if the JSON serialization fails.
§Examples
#[derive(Serialize)]
struct User {
id: u32,
name: String,
}
let user = User {
id: 1,
name: String::from("Alice"),
};
// Create a body containing the JSON representation of user
let body = builder.json(&user)?;Trait Implementations§
Source§impl AsRef<Clock> for HttpBodyBuilder
impl AsRef<Clock> for HttpBodyBuilder
Source§impl AsRef<HttpBodyBuilder> for HttpClient
impl AsRef<HttpBodyBuilder> for HttpClient
Source§fn as_ref(&self) -> &HttpBodyBuilder
fn as_ref(&self) -> &HttpBodyBuilder
Source§impl Clone for HttpBodyBuilder
impl Clone for HttpBodyBuilder
Source§fn clone(&self) -> HttpBodyBuilder
fn clone(&self) -> HttpBodyBuilder
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more