Skip to main content

HttpClientBuilder

Struct HttpClientBuilder 

Source
pub struct HttpClientBuilder { /* private fields */ }
Expand description

Builder for constructing an [HttpClient] with a layered tower middleware stack.

Implementations§

Source§

impl HttpClientBuilder

Source

pub fn new() -> Self

Create a new builder with default configuration

Source

pub fn with_config(config: HttpClientConfig) -> Self

Create a builder with a specific configuration

Source

pub fn timeout(self, timeout: Duration) -> Self

Set the per-request timeout

This timeout applies to each individual HTTP request/attempt. If retries are enabled, each retry attempt gets its own timeout.

Source

pub fn total_timeout(self, timeout: Duration) -> Self

Set the total timeout spanning all retry attempts

When set, the entire operation (including all retries and backoff delays) must complete within this duration. If the deadline is exceeded, the request fails with HttpError::DeadlineExceeded(total_timeout).

Source

pub fn user_agent(self, user_agent: impl Into<String>) -> Self

Set the user agent string

Source

pub fn retry(self, retry: Option<RetryConfig>) -> Self

Set the retry configuration

Source

pub fn max_body_size(self, size: usize) -> Self

Set the maximum response body size

Source

pub fn transport(self, transport: TransportSecurity) -> Self

Set transport security mode

Use TransportSecurity::AllowInsecureHttp only for testing with mock servers.

Source

pub fn allow_insecure_http(self) -> Self

Allow insecure HTTP connections (for testing only)

Equivalent to .transport(TransportSecurity::AllowInsecureHttp).

WARNING: This should only be used for local testing with mock servers. Never use in production as it exposes traffic to interception.

§Compile-time Safety

This method is only available in debug builds or when the allow-insecure-http feature is explicitly enabled. This prevents accidental use in production.

To use in release builds (e.g., for integration tests), add:

[features]
allow-insecure-http = []
Source

pub fn with_otel(self) -> Self

Enable OpenTelemetry tracing layer

When enabled, creates spans for outbound requests with HTTP metadata and injects W3C trace context headers (when otel feature is enabled).

Source

pub fn with_auth_layer( self, wrap: impl FnOnce(BoxCloneService<Request<Full<Bytes>>, Response<ResponseBody>, HttpError>) -> BoxCloneService<Request<Full<Bytes>>, Response<ResponseBody>, HttpError> + Send + 'static, ) -> Self

Insert an optional auth layer between retry and timeout in the stack.

Stack position: … → Retry → **this layer** → Timeout → …

The layer sits inside the retry loop so each attempt re-executes it (e.g. re-reads a refreshed bearer token). Only one auth layer can be set; a second call replaces the first.

Source

pub fn buffer_capacity(self, capacity: usize) -> Self

Set the buffer capacity for concurrent request handling

The HTTP client uses an internal buffer to allow concurrent requests without external locking. This sets the maximum number of requests that can be queued.

Note: A capacity of 0 is invalid and will be clamped to 1. Tower’s Buffer panics with capacity=0, so we enforce minimum of 1.

Source

pub fn max_redirects(self, max_redirects: usize) -> Self

Set the maximum number of redirects to follow

Set to 0 to disable redirect following (3xx responses pass through as-is). Default: 10

Source

pub fn no_redirects(self) -> Self

Disable redirect following

Equivalent to .max_redirects(0). When disabled, 3xx responses are returned to the caller without following the Location header.

Source

pub fn redirect(self, config: RedirectConfig) -> Self

Set the redirect policy configuration

Use this to configure redirect security settings:

  • same_origin_only: Only follow redirects to the same host
  • strip_sensitive_headers: Remove Authorization/Cookie on cross-origin
  • allow_https_downgrade: Allow HTTPS → HTTP redirects (not recommended)
§Example
let client = HttpClient::builder()
    .redirect(RedirectConfig::permissive()) // Allow all redirects with header stripping
    .build()?;
Source

pub fn pool_idle_timeout(self, timeout: Option<Duration>) -> Self

Set the idle connection timeout for the connection pool

Connections that remain idle for longer than this duration will be closed and removed from the pool. Default: 90 seconds.

Set to None to disable idle timeout (connections kept indefinitely).

Source

pub fn pool_max_idle_per_host(self, max: usize) -> Self

Set the maximum number of idle connections per host

Limits how many idle connections are kept in the pool for each host. Default: 32.

  • Setting to 0 disables connection reuse entirely
  • Setting too high may waste resources on rarely-used connections
Source

pub fn build(self) -> Result<HttpClient, HttpError>

Build the HTTP client with all configured layers

§Errors

Returns an error if TLS initialization fails or configuration is invalid

Trait Implementations§

Source§

impl Default for HttpClientBuilder

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> ServiceExt for T

Source§

fn decompression(self) -> Decompression<Self>
where Self: Sized,

Decompress response bodies. Read more
Source§

fn trace_for_http(self) -> Trace<Self, SharedClassifier<ServerErrorsAsFailures>>
where Self: Sized,

High level tracing that classifies responses using HTTP status codes. Read more
Source§

fn trace_for_grpc(self) -> Trace<Self, SharedClassifier<GrpcErrorsAsFailures>>
where Self: Sized,

High level tracing that classifies responses using gRPC headers. Read more
Source§

fn follow_redirects(self) -> FollowRedirect<Self>
where Self: Sized,

Follow redirect resposes using the Standard policy. Read more
Source§

fn set_request_id<M>( self, header_name: HeaderName, make_request_id: M, ) -> SetRequestId<Self, M>
where Self: Sized, M: MakeRequestId,

Add request id header and extension. Read more
Source§

fn set_x_request_id<M>(self, make_request_id: M) -> SetRequestId<Self, M>
where Self: Sized, M: MakeRequestId,

Add request id header and extension, using x-request-id as the header name. Read more
Source§

fn propagate_request_id( self, header_name: HeaderName, ) -> PropagateRequestId<Self>
where Self: Sized,

Propgate request ids from requests to responses. Read more
Source§

fn propagate_x_request_id(self) -> PropagateRequestId<Self>
where Self: Sized,

Propgate request ids from requests to responses, using x-request-id as the header name. Read more
Source§

fn request_body_limit(self, limit: usize) -> RequestBodyLimit<Self>
where Self: Sized,

Intercept requests with over-sized payloads and convert them into 413 Payload Too Large responses. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more