pub struct HttpClientBuilder { /* private fields */ }Expand description
Builder for creating and configuring an HTTP client.
This builder follows the builder pattern, allowing you to customize
various aspects of the HttpClient before creating it.
Each configuration method returns self for method chaining.
By default, the builder is configured to use a standard pipeline that includes
resilience features and observability (logging, metrics).
This behavior can be modified with methods like minimal_pipeline
or custom_pipeline.
§Construction
The builder instance is created using the HttpClient::builder_tokio method, or
the free-standing custom::create_builder function
for a custom transport.
Implementations§
Source§impl HttpClientBuilder
impl HttpClientBuilder
Sourcepub fn name(self, name: impl Into<Cow<'static, str>>) -> Self
pub fn name(self, name: impl Into<Cow<'static, str>>) -> Self
Sets the name for the HTTP client.
The name is used in logging and metrics to identify the HTTP client instance. The name should
follow the snake_case convention. By default, the client is named “http_client”.
Sourcepub fn insecure_allow_http(self) -> Self
pub fn insecure_allow_http(self) -> Self
Allows insecure HTTP connections.
By default, the client only permits HTTPS connections. This method enables both HTTP and HTTPS requests. Use this for testing or internal networks only.
§Security
HTTP connections are unencrypted and can be intercepted. Use with caution!
Sourcepub const fn connect_timeout(self, timeout: Duration) -> Self
pub const fn connect_timeout(self, timeout: Duration) -> Self
Sets the connection timeout duration.
This sets how long to wait for a connection to be established before giving up. If not specified, a default value of 30 seconds will be used.
Sourcepub fn connection_keep_alive(self, mode: ConnectionKeepAlive) -> Self
pub fn connection_keep_alive(self, mode: ConnectionKeepAlive) -> Self
Configures how HTTP connections are kept alive.
Keep-alive maintains open or idle connections, reducing latency for subsequent requests by avoiding the overhead of establishing new TCP connections.
By default, this value is set to ConnectionKeepAlive::disabled.
Sourcepub const fn response_body_options(self, options: HttpBodyOptions) -> Self
pub const fn response_body_options(self, options: HttpBodyOptions) -> Self
Sets the body options applied to every response produced by this client.
HttpBodyOptions controls body-level policies such as the buffer
limit (maximum memory used when buffering via
HttpBody::into_buffered) and the
idle timeout between body frames.
By default, HttpBodyOptions::default() is used.
§Example
let options = HttpBodyOptions::default()
.buffer_limit(4 * 1024 * 1024)
.timeout(Duration::from_secs(30));
let client = builder.response_body_options(options).build();Sourcepub fn minimal_pipeline(self) -> Self
pub fn minimal_pipeline(self) -> Self
Enables the minimal pipeline mode for the client.
In this mode, the client uses only the Dispatch handler directly without any middleware,
giving you complete control but without features like logging or metrics. This is useful
when you need a streamlined client with minimal overhead.
Sourcepub fn custom_pipeline<F, R>(self, factory: F) -> Self
pub fn custom_pipeline<F, R>(self, factory: F) -> Self
Configures the client to use a custom request pipeline instead of the default standard pipeline.
By default, the HTTP client uses a standard pipeline that includes common middleware for handling requests and responses. This method allows you to replace that pipeline with your own implementation, giving you complete control over request processing.
The factory function receives:
- A
Dispatchhandler that handles the actual HTTP communication. - A
PipelineContextwith additional context information.
In your callback, you can provide your own stack of middleware with the dispatch handler at the bottom. Each middleware can add functionality like logging, authentication, caching, or custom request/response transformations. The middleware forms a chain where each one can process the request before passing it to the next handler in the chain.
§Examples
fn configure_builder(mut builder: HttpClientBuilder) -> HttpClientBuilder {
builder.custom_pipeline(move |dispatch, ctx| {
let stack = (
Logging::layer(ctx.clock(), ctx.redaction_engine()),
HttpRetry::layer("my_retry", ctx.resilience_context())
.http_configure_defaults()
.max_retry_attempts(1),
dispatch,
);
stack.into_service()
})
}Sourcepub fn tls_options(self, tls_options: TlsOptions) -> Self
pub fn tls_options(self, tls_options: TlsOptions) -> Self
Sets TLS options for this client.
Use TlsOptions::builder_rustls() for the rustls backend,
or TlsOptions::builder_native_tls() for the platform native TLS backend.
The rustls backend also supports mutual TLS (mTLS) via the builder’s
client_identity method.
§Example
let client = builder
.tls_options(TlsOptions::builder_rustls().build())
.build();Sourcepub fn supported_http_versions(self, versions: &[Version]) -> Self
pub fn supported_http_versions(self, versions: &[Version]) -> Self
Sets the supported HTTP versions for the client.
The default is HTTP/1.1 and HTTP/2. This method allows you to change which HTTP protocol versions the client will use when connecting to servers.
Sourcepub fn meter_provider(self, meter_provider: &dyn MeterProvider) -> Self
pub fn meter_provider(self, meter_provider: &dyn MeterProvider) -> Self
Sets a custom OpenTelemetry meter provider for the client.
The given MeterProvider is used to collect this client’s metrics. By
default, the client uses the global meter provider; use this method to
override it for this client instance.
§Performance
For thread-isolated runtimes, prefer a per-thread meter provider to avoid the lock contention that a global meter provider can cause.
Sourcepub fn standard_pipeline<F>(self, configure: F) -> Selfwhere
F: Fn(StandardRequestPipeline, PipelineContext) -> StandardRequestPipeline + Send + Sync + 'static,
pub fn standard_pipeline<F>(self, configure: F) -> Selfwhere
F: Fn(StandardRequestPipeline, PipelineContext) -> StandardRequestPipeline + Send + Sync + 'static,
Configures the standard pipeline with custom settings.
This method allows you to customize the standard pipeline (which includes resilience features and observability) by providing a configuration function that receives the current pipeline and returns a modified version.
See StandardRequestPipeline for more details on the defaults.
§Multiple Calls
Multiple consecutive calls to this method are additive - each call receives the
pipeline configured by the previous call. However, if you switch to a different
pipeline type (e.g., minimal_pipeline) and then call
this method again, it will receive a fresh default StandardRequestPipeline rather than
the previously configured one.
§Example
let client = builder
.standard_pipeline(|pipeline, _context| {
// Change the attempt timeout to 5 seconds
pipeline.attempt_timeout(|timeout| timeout.timeout(Duration::from_secs(5)))
})
.build();Sourcepub fn base_uri(self, base_uri: impl Into<BaseUri>) -> Self
pub fn base_uri(self, base_uri: impl Into<BaseUri>) -> Self
Sets the base URI for the client.
This setting overrides any endpoint set in the Uri you pass to the
request methods, leading to three possible scenarios:
HttpClientBuilder::base_uriis set: theBaseUrion the request’sUriis ignored and the client uses the providedBaseUriinstead.HttpClientBuilder::base_uriis not set, but the requestUrihas aBaseUri: the client uses theBaseUrifrom the request’sUri.- No endpoint is set on either side: the request fails with a validation
HttpError.
let client = HttpClient::builder_fake(FakeHandler::default(), FakeDeps::default())
.base_uri(BaseUri::from_static("https://example.com"))
.build();
let response = client.get("/foo/bar").fetch().await?;Sourcepub fn router(self, router: Router) -> Self
pub fn router(self, router: Router) -> Self
Configures the Router used to resolve the destination BaseUri for each request.
A router can expose multiple alternative endpoints (e.g. a primary and one or more fallback endpoints). When the configured router has alternatives, the standard pipeline automatically enables retry/hedging on connection-unavailable errors so subsequent attempts can target a different endpoint.
This setting and HttpClientBuilder::base_uri are mutually exclusive shortcuts for the
same underlying configuration; whichever is called last wins. Calling base_uri(uri) is
equivalent to router(Router::fixed(uri)).
§Examples
let client = HttpClient::builder_fake(FakeHandler::default(), FakeDeps::default())
.router(Router::fallback(
BaseUri::from_static("https://primary.example.com/"),
BaseUri::from_static("https://secondary.example.com/"),
))
.build();Sourcepub fn http2_options(self, options: Http2Options) -> Self
pub fn http2_options(self, options: Http2Options) -> Self
Configures HTTP/2 options for the client.
This method allows you to customize HTTP/2-specific settings for connections created by the client. These settings only apply when the client negotiates HTTP/2 connections.
§Examples
let client = builder
.http2_options(Http2Options::default().initial_max_send_streams(100))
.build();Sourcepub fn connection_pool_options(self, options: ConnectionPoolOptions) -> Self
pub fn connection_pool_options(self, options: ConnectionPoolOptions) -> Self
Configures connection pool options for the client.
This method allows you to configure how the client manages its connection pool. The connection pool reuses existing connections to reduce the overhead and latency of establishing new connections for each request.
§Examples
let client = builder
.connection_pool_options(
ConnectionPoolOptions::default()
.max_connections(50)
.connection_idle_timeout(Duration::from_secs(300)),
)
.build();Sourcepub fn redaction_engine(self, redaction_engine: &RedactionEngine) -> Self
pub fn redaction_engine(self, redaction_engine: &RedactionEngine) -> Self
Sets the redaction engine for the client.
The RedactionEngine is used to redact sensitive information from requests and responses.
This is particularly useful for logging and telemetry, where you want to avoid exposing
sensitive data such as authentication tokens, personal information, or other confidential
information.
Sourcepub fn build(self) -> HttpClient
pub fn build(self) -> HttpClient
Builds the configured HttpClient.
This finalizes all configuration and returns a ready-to-use client that reflects every setting applied to this builder.
Trait Implementations§
Source§impl Clone for HttpClientBuilder
impl Clone for HttpClientBuilder
Source§fn clone(&self) -> HttpClientBuilder
fn clone(&self) -> HttpClientBuilder
1.0.0 (const: unstable) · Source§fn clone_from(&mut self, source: &Self)
fn clone_from(&mut self, source: &Self)
source. Read more