Skip to main content

Crate http_extensions

Crate http_extensions 

Source
Expand description

Shared HTTP types and extension traits for clients and servers.

This crate provides common HTTP functionality built on the popular http crate, including flexible body handling, unified error types, and ergonomic extension traits for working with HTTP requests and responses.

§Core Types

§Extension Traits

The crate provides extension traits that add convenience methods to standard HTTP types:

§Quick Start

Here’s a complete example showing how to create an HTTP client, build a request, and validate the response:

// Create a body builder for constructing request/response bodies
let body_builder = HttpBodyBuilder::new_fake();

// Create a fake handler that returns a successful response
// (This uses the `test-util` feature for testing; similar workflow applies to real clients)
let handler = FakeHandler::from(
    HttpResponseBuilder::new(&body_builder)
        .status(200)
        .header("Content-Type", "application/json")
        .text(r#"{"message": "Success"}"#)
        .build()?,
);

// Build and send an HTTP request using the handler
let response = handler
    .request_builder()
    .get("https://api.example.com/data")
    .header("Authorization", "Bearer token")
    .fetch()
    .await?;

// Validate that the response succeeded (returns error for `4xx/5xx` status codes)
let validated_response = response.ensure_success()?;

println!("response status: {}", validated_response.status());

Note: This example uses the test-util feature to create a FakeHandler for testing. In production code, you would use a real HTTP client that implements the RequestHandler trait, but the workflow remains the same: build requests with HttpRequestBuilder, send them through a handler, and validate responses with StatusExt::ensure_success.

§Integration with the HTTP Ecosystem

This crate builds on the popular http crate rather than inventing new types:

§Examples

§Validating Response Status

// Check if the response succeeded and return an error if not
let validated_response = response.ensure_success()?;

§Creating Request Bodies

// Create different body types
let text_body = builder.text("Hello, world!");
let binary_body = builder.slice(&[1, 2, 3, 4]);
let empty_body = builder.empty();

§Building HTTP Requests

let request = HttpRequestBuilder::new(&body_builder)
    .get("https://api.example.com/data")
    .text("Hello World")
    .build()
    .unwrap();

§Building HTTP Responses

let response = HttpResponseBuilder::new(&body_builder)
    .status(200)
    .header("Content-Type", "text/plain")
    .body(body_builder.text("Success"))
    .build()
    .unwrap();

§Building Middleware with RequestHandler

struct LoggingMiddleware<S> {
    inner: S,
}

impl<S: RequestHandler> Service<HttpRequest> for LoggingMiddleware<S> {
    type Out = Result<HttpResponse>;

    async fn execute(&self, request: HttpRequest) -> Self::Out {
        println!("Processing request to: {}", request.uri());
        let response = self.inner.execute(request).await?;
        println!("Response status: {}", response.status());
        Ok(response)
    }
}

§Testing with FakeHandler

The FakeHandler type (available with the test-util feature) lets you mock HTTP responses for testing without making actual network requests. This is useful for unit testing code that depends on HTTP clients.

§Features

  • json - Enables JSON serialization/deserialization support via Json type
  • test-util - Enables fake implementations for testing

§Memory Management

Bodies created through HttpBodyBuilder use memory pools from bytesbuf to reduce allocation overhead. When body data is consumed, memory is automatically recycled for future requests. This makes the crate particularly efficient for high-throughput scenarios.

Modules§

_documentation
Longer form documentation for http_extensions.
routing
Router primitives for resolving the BaseUri of an outgoing request.
timeout
Timeout types for controlling HTTP request and response duration limits.

Structs§

FakeHandlertest-util
Simulates HTTP responses for testing without making actual network requests.
HttpBody
A flexible HTTP body container for various data types.
HttpBodyBuilder
Builder for creating optimized HTTP bodies.
HttpBodyOptions
Options for configuring body-level behavior.
HttpError
A unified HTTP error type.
HttpRequestBuilder
A fluent builder for creating HTTP requests.
HttpResponseBuilder
A fluent builder for creating HTTP responses.
Jsonjson
A lazy JSON parser that defers deserialization until requested.
JsonErrorjson
Error type for JSON serialization and deserialization operations.
UriTemplateLabel
A label for the URL template that can be attached to HTTP requests as an extension.

Traits§

ExtensionsExt
Extensions for http::Extensions.
HeaderMapExt
Header value extraction and parsing.
HeaderValueExt
Construction of HeaderValue from shared byte buffers.
HttpRequestBuilderExt
Extension trait for types that implement RequestHandler and AsRef<HttpBodyBuilder>.
HttpRequestExt
Request cloning with body support.
RequestExt
Extensions for HTTP requests.
RequestHandler
Trait alias for Service<HttpRequest, Out = Result<HttpResponse>>.
ResponseExt
Response recovery classification with Retry-After support.
StatusExt
Status code validation and recovery classification.

Type Aliases§

HttpRequest
Specialized HTTP request that uses the HttpBody type for the body.
HttpResponse
Specialized HTTP response that uses the HttpBody type for the body.
Result
A convenient type alias for results in this crate.