pub struct ClientBuilder { /* private fields */ }Expand description
A ClientBuilder can be used to create a Client with custom configuration.
Implementations§
Source§impl ClientBuilder
impl ClientBuilder
Sourcepub fn transport_config(self, config: TransportConfigOptions) -> ClientBuilder
pub fn transport_config(self, config: TransportConfigOptions) -> ClientBuilder
Replace the transport-layer configuration as a reusable group.
Sourcepub fn pool_config(self, config: PoolConfigOptions) -> ClientBuilder
pub fn pool_config(self, config: PoolConfigOptions) -> ClientBuilder
Replace the connection-pool configuration as a reusable group.
Sourcepub fn tls_config(self, config: TlsConfigOptions) -> ClientBuilder
pub fn tls_config(self, config: TlsConfigOptions) -> ClientBuilder
Replace the TLS configuration as a reusable group.
Sourcepub fn protocol_config(self, config: ProtocolConfigOptions) -> ClientBuilder
pub fn protocol_config(self, config: ProtocolConfigOptions) -> ClientBuilder
Replace the protocol configuration as a reusable group.
Sourcepub fn proxy_config(self, config: ProxyConfigOptions) -> ClientBuilder
pub fn proxy_config(self, config: ProxyConfigOptions) -> ClientBuilder
Replace the proxy configuration as a reusable group.
Sourcepub fn build(self) -> Result<Client>
pub fn build(self) -> Result<Client>
Returns a Client that uses this ClientBuilder configuration.
§Errors
This method fails if a TLS backend cannot be initialized, or the resolver cannot load the system configuration.
Sourcepub fn user_agent<V>(self, value: V) -> ClientBuilder
pub fn user_agent<V>(self, value: V) -> ClientBuilder
Sets the User-Agent header to be used by this client.
§Example
// Name your user agent after your app?
static APP_USER_AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"),);
let client = hpx::Client::builder().user_agent(APP_USER_AGENT).build()?;
let res = client.get("https://www.rust-lang.org").send().await?;Sourcepub fn default_headers(self, headers: HeaderMap) -> ClientBuilder
pub fn default_headers(self, headers: HeaderMap) -> ClientBuilder
Sets the default headers for every request.
§Example
use hpx::header;
let mut headers = header::HeaderMap::new();
headers.insert("X-MY-HEADER", header::HeaderValue::from_static("value"));
// Consider marking security-sensitive headers with `set_sensitive`.
let mut auth_value = header::HeaderValue::from_static("secret");
auth_value.set_sensitive(true);
headers.insert(header::AUTHORIZATION, auth_value);
// get a client builder
let client = hpx::Client::builder().default_headers(headers).build()?;
let res = client.get("https://www.rust-lang.org").send().await?;Override the default headers:
use hpx::header;
let mut headers = header::HeaderMap::new();
headers.insert("X-MY-HEADER", header::HeaderValue::from_static("value"));
// get a client builder
let client = hpx::Client::builder().default_headers(headers).build()?;
let res = client
.get("https://www.rust-lang.org")
.header("X-MY-HEADER", "new_value")
.send()
.await?;Sourcepub fn orig_headers(self, orig_headers: OrigHeaderMap) -> ClientBuilder
pub fn orig_headers(self, orig_headers: OrigHeaderMap) -> ClientBuilder
Sets the original headers for every request.
Available on crate feature cookies only.
cookies only.Enable a persistent cookie store for the client.
Cookies received in responses will be preserved and included in additional requests.
By default, no cookie store is used.
§Optional
This requires the optional cookies feature to be enabled.
Available on crate feature cookies only.
cookies only.Set the persistent cookie store for the client.
Cookies received in responses will be passed to this store, and additional requests will query this store for cookies.
By default, no cookie store is used.
§Optional
This requires the optional cookies feature to be enabled.
Sourcepub fn gzip(self, enable: bool) -> ClientBuilder
Available on crate feature gzip only.
pub fn gzip(self, enable: bool) -> ClientBuilder
gzip only.Enable auto gzip decompression by checking the Content-Encoding response header.
If auto gzip decompression is turned on:
- When sending a request and if the request’s headers do not already contain an
Accept-EncodingandRangevalues, theAccept-Encodingheader is set togzip. The request body is not automatically compressed. - When receiving a response, if its headers contain a
Content-Encodingvalue ofgzip, bothContent-EncodingandContent-Lengthare removed from the headers’ set. The response body is automatically decompressed.
If the gzip feature is turned on, the default option is enabled.
§Optional
This requires the optional gzip feature to be enabled
Sourcepub fn brotli(self, enable: bool) -> ClientBuilder
Available on crate feature brotli only.
pub fn brotli(self, enable: bool) -> ClientBuilder
brotli only.Enable auto brotli decompression by checking the Content-Encoding response header.
If auto brotli decompression is turned on:
- When sending a request and if the request’s headers do not already contain an
Accept-EncodingandRangevalues, theAccept-Encodingheader is set tobr. The request body is not automatically compressed. - When receiving a response, if its headers contain a
Content-Encodingvalue ofbr, bothContent-EncodingandContent-Lengthare removed from the headers’ set. The response body is automatically decompressed.
If the brotli feature is turned on, the default option is enabled.
§Optional
This requires the optional brotli feature to be enabled
Sourcepub fn zstd(self, enable: bool) -> ClientBuilder
Available on crate feature zstd only.
pub fn zstd(self, enable: bool) -> ClientBuilder
zstd only.Enable auto zstd decompression by checking the Content-Encoding response header.
If auto zstd decompression is turned on:
- When sending a request and if the request’s headers do not already contain an
Accept-EncodingandRangevalues, theAccept-Encodingheader is set tozstd. The request body is not automatically compressed. - When receiving a response, if its headers contain a
Content-Encodingvalue ofzstd, bothContent-EncodingandContent-Lengthare removed from the headers’ set. The response body is automatically decompressed.
If the zstd feature is turned on, the default option is enabled.
§Optional
This requires the optional zstd feature to be enabled
Sourcepub fn deflate(self, enable: bool) -> ClientBuilder
Available on crate feature deflate only.
pub fn deflate(self, enable: bool) -> ClientBuilder
deflate only.Enable auto deflate decompression by checking the Content-Encoding response header.
If auto deflate decompression is turned on:
- When sending a request and if the request’s headers do not already contain an
Accept-EncodingandRangevalues, theAccept-Encodingheader is set todeflate. The request body is not automatically compressed. - When receiving a response, if it’s headers contain a
Content-Encodingvalue that equals todeflate, both valuesContent-EncodingandContent-Lengthare removed from the headers’ set. The response body is automatically decompressed.
If the deflate feature is turned on, the default option is enabled.
§Optional
This requires the optional deflate feature to be enabled
Sourcepub fn no_zstd(self) -> ClientBuilder
pub fn no_zstd(self) -> ClientBuilder
Disable auto response body zstd decompression.
This method exists even if the optional zstd feature is not enabled.
This can be used to ensure a Client doesn’t use zstd decompression
even if another dependency were to enable the optional zstd feature.
Sourcepub fn no_gzip(self) -> ClientBuilder
pub fn no_gzip(self) -> ClientBuilder
Disable auto response body gzip decompression.
This method exists even if the optional gzip feature is not enabled.
This can be used to ensure a Client doesn’t use gzip decompression
even if another dependency were to enable the optional gzip feature.
Sourcepub fn no_brotli(self) -> ClientBuilder
pub fn no_brotli(self) -> ClientBuilder
Disable auto response body brotli decompression.
This method exists even if the optional brotli feature is not enabled.
This can be used to ensure a Client doesn’t use brotli decompression
even if another dependency were to enable the optional brotli feature.
Sourcepub fn no_deflate(self) -> ClientBuilder
pub fn no_deflate(self) -> ClientBuilder
Disable auto response body deflate decompression.
This method exists even if the optional deflate feature is not enabled.
This can be used to ensure a Client doesn’t use deflate decompression
even if another dependency were to enable the optional deflate feature.
Sourcepub fn redirect(self, policy: Policy) -> ClientBuilder
pub fn redirect(self, policy: Policy) -> ClientBuilder
Set a RedirectPolicy for this client.
Default will follow redirects up to a maximum of 10.
Sourcepub fn referer(self, enable: bool) -> ClientBuilder
pub fn referer(self, enable: bool) -> ClientBuilder
Enable or disable automatic setting of the Referer header.
Default is true.
Sourcepub fn retry(self, policy: Policy) -> ClientBuilder
pub fn retry(self, policy: Policy) -> ClientBuilder
Set a request retry policy.
Sourcepub fn max_retries_per_request(self, max: u32) -> ClientBuilder
pub fn max_retries_per_request(self, max: u32) -> ClientBuilder
Set the maximum number of retries allowed for a single logical request.
This is a convenience wrapper around
retry::Policy::max_retries_per_request that preserves the rest of
the currently configured retry policy.
Sourcepub fn system_proxy(self) -> ClientBuilder
pub fn system_proxy(self) -> ClientBuilder
Enable automatic detection of system proxy settings from environment
variables (HTTP_PROXY, HTTPS_PROXY, ALL_PROXY, NO_PROXY) and,
when the system-proxy feature is active, OS-level proxy configuration.
System proxy detection is enabled by default. Call this method to explicitly opt in (no-op if already enabled).
§Example
let client = hpx::Client::builder().system_proxy().build().unwrap();Sourcepub fn proxy(self, proxy: Proxy) -> ClientBuilder
pub fn proxy(self, proxy: Proxy) -> ClientBuilder
Sourcepub fn proxy_pool(self, pool: ProxyPool) -> ClientBuilder
pub fn proxy_pool(self, pool: ProxyPool) -> ClientBuilder
Configure a proxy pool middleware for request-level proxy rotation.
This middleware selects a proxy for each request based on the configured
crate::proxy_pool::ProxyPoolStrategy. When this is set, automatic
system proxy detection is disabled.
Sourcepub fn no_proxy(self) -> ClientBuilder
pub fn no_proxy(self) -> ClientBuilder
Clear all Proxies, so Client will use no proxy anymore.
§Note
To add a proxy exclusion list, use crate::proxy::Proxy::no_proxy() on all desired proxies instead.
This also disables the automatic usage of the “system” proxy.
Sourcepub fn timeout(self, timeout: Duration) -> ClientBuilder
pub fn timeout(self, timeout: Duration) -> ClientBuilder
Enables a request timeout.
The timeout is applied from when the request starts connecting until the response body has finished.
Default is no timeout.
Sourcepub fn read_timeout(self, timeout: Duration) -> ClientBuilder
pub fn read_timeout(self, timeout: Duration) -> ClientBuilder
Set a timeout for only the read phase of a Client.
Default is None.
Sourcepub fn connect_timeout(self, timeout: Duration) -> ClientBuilder
pub fn connect_timeout(self, timeout: Duration) -> ClientBuilder
Set a timeout for only the connect phase of a Client.
Default is None.
§Note
This requires the futures be executed in a tokio runtime with a tokio timer enabled.
Sourcepub fn timeout_global(self, timeout: Option<Duration>) -> ClientBuilder
pub fn timeout_global(self, timeout: Option<Duration>) -> ClientBuilder
Timeout for the entire request lifecycle (end-to-end).
This is the global timeout covering all phases: DNS resolution, connection, request sending, and response body reading.
Default is None.
Sourcepub fn timeout_per_call(self, timeout: Option<Duration>) -> ClientBuilder
pub fn timeout_per_call(self, timeout: Option<Duration>) -> ClientBuilder
Timeout for a single call attempt when following redirects.
Resets after each redirect.
Default is None.
Sourcepub fn timeout_resolve(self, timeout: Option<Duration>) -> ClientBuilder
pub fn timeout_resolve(self, timeout: Option<Duration>) -> ClientBuilder
Timeout for DNS resolution.
Default is None.
Sourcepub fn timeout_send_request(self, timeout: Option<Duration>) -> ClientBuilder
pub fn timeout_send_request(self, timeout: Option<Duration>) -> ClientBuilder
Timeout for sending request headers (not the body).
Default is None.
Sourcepub fn timeout_await_100(self, timeout: Option<Duration>) -> ClientBuilder
pub fn timeout_await_100(self, timeout: Option<Duration>) -> ClientBuilder
Timeout for awaiting a 100 Continue response.
Default is 1 second.
Sourcepub fn timeout_send_body(self, timeout: Option<Duration>) -> ClientBuilder
pub fn timeout_send_body(self, timeout: Option<Duration>) -> ClientBuilder
Timeout for sending the request body.
Default is None.
Sourcepub fn timeout_recv_response(self, timeout: Option<Duration>) -> ClientBuilder
pub fn timeout_recv_response(self, timeout: Option<Duration>) -> ClientBuilder
Timeout for receiving response headers (not the body).
Default is None.
Sourcepub fn timeout_recv_body(self, timeout: Option<Duration>) -> ClientBuilder
pub fn timeout_recv_body(self, timeout: Option<Duration>) -> ClientBuilder
Timeout for receiving the response body.
Default is None.
Sourcepub fn max_response_header_size(self, size: Option<usize>) -> ClientBuilder
pub fn max_response_header_size(self, size: Option<usize>) -> ClientBuilder
Set the maximum size of HTTP response headers in bytes.
This protects against servers sending unreasonably large response headers.
Default is 64KB (65536 bytes). Set to None to disable the limit.
Sourcepub fn connection_verbose(self, verbose: bool) -> ClientBuilder
pub fn connection_verbose(self, verbose: bool) -> ClientBuilder
Set whether connections should emit verbose logs.
Enabling this option will emit log messages at the TRACE level
for read and write operations on connections.
Sourcepub fn pool_idle_timeout<D>(self, val: D) -> ClientBuilder
pub fn pool_idle_timeout<D>(self, val: D) -> ClientBuilder
Set an optional timeout for idle sockets being kept-alive.
Pass None to disable timeout.
Default is 90 seconds.
Sourcepub fn pool_max_idle_per_host(self, max: usize) -> ClientBuilder
pub fn pool_max_idle_per_host(self, max: usize) -> ClientBuilder
Sets the maximum idle connection per host allowed in the pool.
Sourcepub fn pool_max_size(self, max: u32) -> ClientBuilder
pub fn pool_max_size(self, max: u32) -> ClientBuilder
Sets the maximum number of connections in the pool.
Sourcepub fn https_only(self, enabled: bool) -> ClientBuilder
pub fn https_only(self, enabled: bool) -> ClientBuilder
Restrict the Client to be used with HTTPS only requests.
Defaults to false.
Sourcepub fn http1_only(self) -> ClientBuilder
pub fn http1_only(self) -> ClientBuilder
Only use HTTP/1.
Sourcepub fn http2_only(self) -> ClientBuilder
pub fn http2_only(self) -> ClientBuilder
Only use HTTP/2.
Sourcepub fn http1_options(self, options: Http1Options) -> ClientBuilder
Available on crate feature http1 only.
pub fn http1_options(self, options: Http1Options) -> ClientBuilder
http1 only.Sets the HTTP/1 options for the client.
Sourcepub fn max_poll_iterations(self, max_iterations: usize) -> ClientBuilder
Available on crate feature http1 only.
pub fn max_poll_iterations(self, max_iterations: usize) -> ClientBuilder
http1 only.Set the maximum number of HTTP/1 dispatcher iterations per poll cycle.
This bounds how many pipelined HTTP/1 exchanges are processed before the task yields back to the runtime scheduler.
Sourcepub fn http2_options(self, options: Http2Options) -> ClientBuilder
Available on crate feature http2 only.
pub fn http2_options(self, options: Http2Options) -> ClientBuilder
http2 only.Sets the HTTP/2 options for the client.
Sourcepub fn tcp_nodelay(self, enabled: bool) -> ClientBuilder
pub fn tcp_nodelay(self, enabled: bool) -> ClientBuilder
Set whether sockets have TCP_NODELAY enabled.
Default is true.
Sourcepub fn tcp_keepalive<D>(self, val: D) -> ClientBuilder
pub fn tcp_keepalive<D>(self, val: D) -> ClientBuilder
Set that all sockets have SO_KEEPALIVE set with the supplied duration.
If None, the option will not be set.
Default is 15 seconds.
Sourcepub fn tcp_keepalive_interval<D>(self, val: D) -> ClientBuilder
pub fn tcp_keepalive_interval<D>(self, val: D) -> ClientBuilder
Set that all sockets have SO_KEEPALIVE set with the supplied interval.
If None, the option will not be set.
Default is 15 seconds.
Sourcepub fn tcp_keepalive_retries<C>(self, retries: C) -> ClientBuilder
pub fn tcp_keepalive_retries<C>(self, retries: C) -> ClientBuilder
Set that all sockets have SO_KEEPALIVE set with the supplied retry count.
If None, the option will not be set.
Default is 3 retries.
Sourcepub fn tcp_user_timeout<D>(self, val: D) -> ClientBuilder
Available on Android or Fuchsia or Linux only.
pub fn tcp_user_timeout<D>(self, val: D) -> ClientBuilder
Set that all sockets have TCP_USER_TIMEOUT set with the supplied duration.
This option controls how long transmitted data may remain unacknowledged before the connection is force-closed.
If None, the option will not be set.
Default is 30 seconds.
Sourcepub fn tcp_reuse_address(self, enabled: bool) -> ClientBuilder
pub fn tcp_reuse_address(self, enabled: bool) -> ClientBuilder
Set whether sockets have SO_REUSEADDR enabled.
Sourcepub fn tcp_send_buffer_size<S>(self, size: S) -> ClientBuilder
pub fn tcp_send_buffer_size<S>(self, size: S) -> ClientBuilder
Sets the size of the TCP send buffer on this client socket.
On most operating systems, this sets the SO_SNDBUF socket option.
Sourcepub fn tcp_recv_buffer_size<S>(self, size: S) -> ClientBuilder
pub fn tcp_recv_buffer_size<S>(self, size: S) -> ClientBuilder
Sets the size of the TCP receive buffer on this client socket.
On most operating systems, this sets the SO_RCVBUF socket option.
Sourcepub fn tcp_happy_eyeballs_timeout<D>(self, val: D) -> ClientBuilder
pub fn tcp_happy_eyeballs_timeout<D>(self, val: D) -> ClientBuilder
Set timeout for RFC 6555 (Happy Eyeballs) algorithm.
If hostname resolves to both IPv4 and IPv6 addresses and connection cannot be established using preferred address family before timeout elapses, then connector will in parallel attempt connection using other address family.
If None, parallel connection attempts are disabled.
Default is 300 milliseconds.
Sourcepub fn local_address<T>(self, addr: T) -> ClientBuilder
pub fn local_address<T>(self, addr: T) -> ClientBuilder
Bind to a local IP Address.
§Example
use std::net::IpAddr;
let local_addr = IpAddr::from([12, 4, 1, 8]);
let client = hpx::Client::builder()
.local_address(local_addr)
.build()
.unwrap();Sourcepub fn local_addresses<V4, V6>(self, ipv4: V4, ipv6: V6) -> ClientBuilder
pub fn local_addresses<V4, V6>(self, ipv4: V4, ipv6: V6) -> ClientBuilder
Set that all sockets are bound to the configured IPv4 or IPv6 address (depending on host’s preferences) before connection.
§Example
///
use std::net::{Ipv4Addr, Ipv6Addr};
let ipv4 = Ipv4Addr::new(127, 0, 0, 1);
let ipv6 = Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1);
let client = hpx::Client::builder()
.local_addresses(ipv4, ipv6)
.build()
.unwrap();Sourcepub fn interface<T>(self, interface: T) -> ClientBuilder
Available on Android or Fuchsia or illumos or iOS or Linux or macOS or Solaris or tvOS or visionOS or watchOS only.
pub fn interface<T>(self, interface: T) -> ClientBuilder
Bind connections only on the specified network interface.
This option is only available on the following operating systems:
- Android
- Fuchsia
- Linux,
- macOS and macOS-like systems (iOS, tvOS, watchOS and visionOS)
- Solaris and illumos
On Android, Linux, and Fuchsia, this uses the
SO_BINDTODEVICE socket option. On macOS and macOS-like
systems, Solaris, and illumos, this instead uses the IP_BOUND_IF and
IPV6_BOUND_IF socket options (as appropriate).
Note that connections will fail if the provided interface name is not a network interface that currently exists when a connection is established.
§Example
let interface = "lo";
let client = hpx::Client::builder().interface(interface).build()?;Sourcepub fn identity(self, identity: Identity) -> ClientBuilder
pub fn identity(self, identity: Identity) -> ClientBuilder
Sets the identity to be used for client certificate authentication.
Sourcepub fn cert_store(self, store: CertStore) -> ClientBuilder
pub fn cert_store(self, store: CertStore) -> ClientBuilder
Sets the verify certificate store for the client.
This method allows you to specify a custom verify certificate store to be used for TLS connections. By default, the system’s verify certificate store is used.
Sourcepub fn cert_verification(self, cert_verification: bool) -> ClientBuilder
pub fn cert_verification(self, cert_verification: bool) -> ClientBuilder
Controls the use of certificate validation.
Defaults to true.
§Warning
You should think very carefully before using this method. If invalid certificates are trusted, any certificate for any site will be trusted for use. This includes expired certificates. This introduces significant vulnerabilities, and should only be used as a last resort.
Sourcepub fn verify_hostname(self, verify_hostname: bool) -> ClientBuilder
pub fn verify_hostname(self, verify_hostname: bool) -> ClientBuilder
Configures the use of hostname verification when connecting.
Defaults to true.
§Warning
You should think very carefully before you use this method. If hostname verification is not used, any valid certificate for any site will be trusted for use from any other. This introduces a significant vulnerability to man-in-the-middle attacks.
Sourcepub fn tls_sni(self, tls_sni: bool) -> ClientBuilder
pub fn tls_sni(self, tls_sni: bool) -> ClientBuilder
Configures the use of Server Name Indication (SNI) when connecting.
Defaults to true.
Sourcepub fn keylog(self, keylog: KeyLog) -> ClientBuilder
pub fn keylog(self, keylog: KeyLog) -> ClientBuilder
Configures TLS key logging for the client.
Sourcepub fn min_tls_version(self, version: TlsVersion) -> ClientBuilder
pub fn min_tls_version(self, version: TlsVersion) -> ClientBuilder
Set the minimum required TLS version for connections.
By default the TLS backend’s own default is used.
Sourcepub fn max_tls_version(self, version: TlsVersion) -> ClientBuilder
pub fn max_tls_version(self, version: TlsVersion) -> ClientBuilder
Set the maximum allowed TLS version for connections.
By default there’s no maximum.
Sourcepub fn tls_info(self, tls_info: bool) -> ClientBuilder
pub fn tls_info(self, tls_info: bool) -> ClientBuilder
Sourcepub fn tls_options(self, options: TlsOptions) -> ClientBuilder
pub fn tls_options(self, options: TlsOptions) -> ClientBuilder
Sets the TLS options for the client.
Sourcepub fn no_hickory_dns(self) -> ClientBuilder
Available on crate feature hickory-dns only.
pub fn no_hickory_dns(self) -> ClientBuilder
hickory-dns only.Disables the hickory-dns async resolver.
This method exists even if the optional hickory-dns feature is not enabled.
This can be used to ensure a Client doesn’t use the hickory-dns async resolver
even if another dependency were to enable the optional hickory-dns feature.
Sourcepub fn resolve<D>(self, domain: D, addr: SocketAddr) -> ClientBuilder
pub fn resolve<D>(self, domain: D, addr: SocketAddr) -> ClientBuilder
Override DNS resolution for specific domains to a particular IP address.
Warning
Since the DNS protocol has no notion of ports, if you wish to send traffic to a particular port you must include this port in the URI itself, any port in the overridden addr will be ignored and traffic sent to the conventional port for the given scheme (e.g. 80 for http).
Sourcepub fn resolve_to_addrs<D, A>(self, domain: D, addrs: A) -> ClientBuilder
pub fn resolve_to_addrs<D, A>(self, domain: D, addrs: A) -> ClientBuilder
Override DNS resolution for specific domains to particular IP addresses.
Warning
Since the DNS protocol has no notion of ports, if you wish to send traffic to a particular port you must include this port in the URI itself, any port in the overridden addresses will be ignored and traffic sent to the conventional port for the given scheme (e.g. 80 for http).
Sourcepub fn dns_resolver<R>(self, resolver: R) -> ClientBuilderwhere
R: IntoResolve,
pub fn dns_resolver<R>(self, resolver: R) -> ClientBuilderwhere
R: IntoResolve,
Override the DNS resolver implementation.
Pass any type implementing IntoResolve.
Overrides for specific names passed to resolve and resolve_to_addrs will
still be applied on top of this resolver.
Sourcepub fn hooks(self, hooks: Hooks) -> ClientBuilder
pub fn hooks(self, hooks: Hooks) -> ClientBuilder
Adds lifecycle hooks to the client.
Hooks allow you to execute custom logic at different stages of the request lifecycle, such as before sending a request or after receiving a response.
§Example
use std::sync::Arc;
use hpx::hooks::{Hooks, LoggingHook};
let hooks = Hooks::builder()
.before_request(Arc::new(LoggingHook::new()))
.build();
let client = hpx::Client::builder().hooks(hooks).build().unwrap();Sourcepub fn recoveries(self, recoveries: Recoveries) -> ClientBuilder
pub fn recoveries(self, recoveries: Recoveries) -> ClientBuilder
Adds response recovery hooks to the client.
Sourcepub fn on_request<F>(self, hook: F) -> ClientBuilder
pub fn on_request<F>(self, hook: F) -> ClientBuilder
Adds a before-request hook using a closure.
This is a convenience method for adding simple request hooks without
implementing the BeforeRequestHook trait manually.
§Example
use hpx::header;
let client = hpx::Client::builder()
.on_request(|req| {
req.headers_mut().insert(
header::HeaderName::from_static("x-custom"),
header::HeaderValue::from_static("value"),
);
Ok(())
})
.build()
.unwrap();Sourcepub fn on_response<F>(self, hook: F) -> ClientBuilder
pub fn on_response<F>(self, hook: F) -> ClientBuilder
Adds an after-response hook using a closure.
This is a convenience method for adding simple response hooks without
implementing the AfterResponseHook trait manually.
§Example
use http::StatusCode;
let client = hpx::Client::builder()
.on_response(|status, _headers| {
println!("Response status: {}", status);
Ok(())
})
.build()
.unwrap();Sourcepub fn on_status<F, Fut>(self, status: StatusCode, hook: F) -> ClientBuilder
pub fn on_status<F, Fut>(self, status: StatusCode, hook: F) -> ClientBuilder
Adds a status-based response recovery hook using a closure.
Sourcepub fn layer<L>(self, layer: L) -> ClientBuilderwhere
L: Layer<BoxCloneSyncService<Request<Body>, Response<ClientResponseBody>, Box<dyn StdError + Send + Sync>>> + Clone + Send + Sync + 'static,
L::Service: Service<Request<Body>, Response = Response<ClientResponseBody>, Error = Box<dyn StdError + Send + Sync>> + Clone + Send + Sync + 'static,
<L::Service as Service<Request<Body>>>::Future: Send + 'static,
pub fn layer<L>(self, layer: L) -> ClientBuilderwhere
L: Layer<BoxCloneSyncService<Request<Body>, Response<ClientResponseBody>, Box<dyn StdError + Send + Sync>>> + Clone + Send + Sync + 'static,
L::Service: Service<Request<Body>, Response = Response<ClientResponseBody>, Error = Box<dyn StdError + Send + Sync>> + Clone + Send + Sync + 'static,
<L::Service as Service<Request<Body>>>::Future: Send + 'static,
Adds a new Tower Layer to the
request Service which is responsible
for request processing.
Each subsequent invocation of this function will wrap previous layers.
If configured, the timeout will be the outermost layer.
Example usage:
use std::time::Duration;
let client = hpx::Client::builder()
.timeout(Duration::from_millis(200))
.layer(tower::timeout::TimeoutLayer::new(Duration::from_millis(50)))
.build()
.unwrap();Sourcepub fn connector_layer<L>(self, layer: L) -> ClientBuilder
pub fn connector_layer<L>(self, layer: L) -> ClientBuilder
Adds a new Tower Layer to the
base connector Service which
is responsible for connection establishment.a
Each subsequent invocation of this function will wrap previous layers.
If configured, the connect_timeout will be the outermost layer.
Example usage:
use std::time::Duration;
let client = hpx::Client::builder()
// resolved to outermost layer, meaning while we are waiting on concurrency limit
.connect_timeout(Duration::from_millis(200))
// underneath the concurrency check, so only after concurrency limit lets us through
.connector_layer(tower::timeout::TimeoutLayer::new(Duration::from_millis(50)))
.connector_layer(tower::limit::concurrency::ConcurrencyLimitLayer::new(2))
.build()
.unwrap();Sourcepub fn auth(self, auth: AuthMethod) -> ClientBuilder
Available on crate feature auth only.
pub fn auth(self, auth: AuthMethod) -> ClientBuilder
auth only.Adds authentication to the client using the specified method.
The auth layer is added as a Tower middleware that automatically injects authentication headers into every request.
§Example
use hpx::auth::AuthMethod;
let client = hpx::Client::builder()
.auth(AuthMethod::bearer("my-secret-token"))
.build()
.unwrap();Sourcepub fn circuit_breaker(self, config: CircuitBreakerConfig) -> ClientBuilder
pub fn circuit_breaker(self, config: CircuitBreakerConfig) -> ClientBuilder
Adds a circuit breaker middleware to the client.
When the circuit is open (after failure_threshold consecutive failures),
all requests fail fast without making network calls.
§Example
use std::time::Duration;
use hpx::circuit_breaker::CircuitBreakerConfig;
let client = hpx::Client::builder()
.circuit_breaker(CircuitBreakerConfig::new(5).recovery_timeout(Duration::from_secs(30)))
.build()
.unwrap();Sourcepub fn emulation<P>(self, factory: P) -> ClientBuilderwhere
P: EmulationFactory,
pub fn emulation<P>(self, factory: P) -> ClientBuilderwhere
P: EmulationFactory,
Configures the client builder to emulate the specified HTTP context.
This method sets the necessary headers, HTTP/1 and HTTP/2 options configurations, and TLS options config to use the specified HTTP context. It allows the client to mimic the behavior of different versions or setups, which can be useful for testing or ensuring compatibility with various environments.
§Note
This will overwrite the existing configuration. You must set emulation before you can perform subsequent HTTP1/HTTP2/TLS fine-tuning.
§Example
use hpx::{BrowserProfile, Client};
let client = Client::builder()
.emulation(BrowserProfile::Firefox)
.build()
.unwrap();Auto Trait Implementations§
impl !RefUnwindSafe for ClientBuilder
impl !UnwindSafe for ClientBuilder
impl Freeze for ClientBuilder
impl Send for ClientBuilder
impl Sync for ClientBuilder
impl Unpin for ClientBuilder
impl UnsafeUnpin for ClientBuilder
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self>
fn instrument(self, span: Span) -> Instrumented<Self>
Source§fn in_current_span(self) -> Instrumented<Self>
fn in_current_span(self) -> Instrumented<Self>
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more