Skip to main content

ClientBuilder

Struct ClientBuilder 

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

A ClientBuilder can be used to create a Client with custom configuration.

Implementations§

Source§

impl ClientBuilder

Source

pub fn transport_config(self, config: TransportConfigOptions) -> ClientBuilder

Replace the transport-layer configuration as a reusable group.

Source

pub fn pool_config(self, config: PoolConfigOptions) -> ClientBuilder

Replace the connection-pool configuration as a reusable group.

Source

pub fn tls_config(self, config: TlsConfigOptions) -> ClientBuilder

Replace the TLS configuration as a reusable group.

Source

pub fn protocol_config(self, config: ProtocolConfigOptions) -> ClientBuilder

Replace the protocol configuration as a reusable group.

Source

pub fn proxy_config(self, config: ProxyConfigOptions) -> ClientBuilder

Replace the proxy configuration as a reusable group.

Source

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.

Source

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?;
Source

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?;
Source

pub fn orig_headers(self, orig_headers: OrigHeaderMap) -> ClientBuilder

Sets the original headers for every request.

Source

pub fn cookie_store(self, enable: bool) -> ClientBuilder

Available on crate feature 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.

Source

pub fn cookie_provider<C>(self, cookie_store: C) -> ClientBuilder
where C: IntoCookieStore,

Available on crate feature 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.

Source

pub fn gzip(self, enable: bool) -> ClientBuilder

Available on crate feature 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-Encoding and Range values, the Accept-Encoding header is set to gzip. The request body is not automatically compressed.
  • When receiving a response, if its headers contain a Content-Encoding value of gzip, both Content-Encoding and Content-Length are 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

Source

pub fn brotli(self, enable: bool) -> ClientBuilder

Available on crate feature 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-Encoding and Range values, the Accept-Encoding header is set to br. The request body is not automatically compressed.
  • When receiving a response, if its headers contain a Content-Encoding value of br, both Content-Encoding and Content-Length are 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

Source

pub fn zstd(self, enable: bool) -> ClientBuilder

Available on crate feature 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-Encoding and Range values, the Accept-Encoding header is set to zstd. The request body is not automatically compressed.
  • When receiving a response, if its headers contain a Content-Encoding value of zstd, both Content-Encoding and Content-Length are 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

Source

pub fn deflate(self, enable: bool) -> ClientBuilder

Available on crate feature 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-Encoding and Range values, the Accept-Encoding header is set to deflate. The request body is not automatically compressed.
  • When receiving a response, if it’s headers contain a Content-Encoding value that equals to deflate, both values Content-Encoding and Content-Length are 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

Source

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.

Source

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.

Source

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.

Source

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.

Source

pub fn redirect(self, policy: Policy) -> ClientBuilder

Set a RedirectPolicy for this client.

Default will follow redirects up to a maximum of 10.

Source

pub fn referer(self, enable: bool) -> ClientBuilder

Enable or disable automatic setting of the Referer header.

Default is true.

Source

pub fn retry(self, policy: Policy) -> ClientBuilder

Set a request retry policy.

Source

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.

Source

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();
Source

pub fn proxy(self, proxy: Proxy) -> ClientBuilder

Add a Proxy to the list of proxies the Client will use.

§Note

Adding a proxy will disable the automatic usage of the “system” proxy.

§Example
use hpx::{Client, Proxy};

let proxy = Proxy::http("http://proxy:8080").unwrap();
let client = Client::builder().proxy(proxy).build().unwrap();
Source

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.

Source

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.

Source

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.

Source

pub fn read_timeout(self, timeout: Duration) -> ClientBuilder

Set a timeout for only the read phase of a Client.

Default is None.

Source

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.

Source

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.

Source

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.

Source

pub fn timeout_resolve(self, timeout: Option<Duration>) -> ClientBuilder

Timeout for DNS resolution.

Default is None.

Source

pub fn timeout_send_request(self, timeout: Option<Duration>) -> ClientBuilder

Timeout for sending request headers (not the body).

Default is None.

Source

pub fn timeout_await_100(self, timeout: Option<Duration>) -> ClientBuilder

Timeout for awaiting a 100 Continue response.

Default is 1 second.

Source

pub fn timeout_send_body(self, timeout: Option<Duration>) -> ClientBuilder

Timeout for sending the request body.

Default is None.

Source

pub fn timeout_recv_response(self, timeout: Option<Duration>) -> ClientBuilder

Timeout for receiving response headers (not the body).

Default is None.

Source

pub fn timeout_recv_body(self, timeout: Option<Duration>) -> ClientBuilder

Timeout for receiving the response body.

Default is None.

Source

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.

Source

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.

Source

pub fn pool_idle_timeout<D>(self, val: D) -> ClientBuilder
where D: Into<Option<Duration>>,

Set an optional timeout for idle sockets being kept-alive.

Pass None to disable timeout.

Default is 90 seconds.

Source

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

Sets the maximum idle connection per host allowed in the pool.

Source

pub fn pool_max_size(self, max: u32) -> ClientBuilder

Sets the maximum number of connections in the pool.

Source

pub fn https_only(self, enabled: bool) -> ClientBuilder

Restrict the Client to be used with HTTPS only requests.

Defaults to false.

Source

pub fn http1_only(self) -> ClientBuilder

Only use HTTP/1.

Source

pub fn http2_only(self) -> ClientBuilder

Only use HTTP/2.

Source

pub fn http1_options(self, options: Http1Options) -> ClientBuilder

Available on crate feature http1 only.

Sets the HTTP/1 options for the client.

Source

pub fn max_poll_iterations(self, max_iterations: usize) -> ClientBuilder

Available on crate feature 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.

Source

pub fn http2_options(self, options: Http2Options) -> ClientBuilder

Available on crate feature http2 only.

Sets the HTTP/2 options for the client.

Source

pub fn tcp_nodelay(self, enabled: bool) -> ClientBuilder

Set whether sockets have TCP_NODELAY enabled.

Default is true.

Source

pub fn tcp_keepalive<D>(self, val: D) -> ClientBuilder
where D: Into<Option<Duration>>,

Set that all sockets have SO_KEEPALIVE set with the supplied duration.

If None, the option will not be set.

Default is 15 seconds.

Source

pub fn tcp_keepalive_interval<D>(self, val: D) -> ClientBuilder
where D: Into<Option<Duration>>,

Set that all sockets have SO_KEEPALIVE set with the supplied interval.

If None, the option will not be set.

Default is 15 seconds.

Source

pub fn tcp_keepalive_retries<C>(self, retries: C) -> ClientBuilder
where C: Into<Option<u32>>,

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.

Source

pub fn tcp_user_timeout<D>(self, val: D) -> ClientBuilder
where D: Into<Option<Duration>>,

Available on Android or Fuchsia or Linux only.

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.

Source

pub fn tcp_reuse_address(self, enabled: bool) -> ClientBuilder

Set whether sockets have SO_REUSEADDR enabled.

Source

pub fn tcp_send_buffer_size<S>(self, size: S) -> ClientBuilder
where S: Into<Option<usize>>,

Sets the size of the TCP send buffer on this client socket.

On most operating systems, this sets the SO_SNDBUF socket option.

Source

pub fn tcp_recv_buffer_size<S>(self, size: S) -> ClientBuilder
where S: Into<Option<usize>>,

Sets the size of the TCP receive buffer on this client socket.

On most operating systems, this sets the SO_RCVBUF socket option.

Source

pub fn tcp_happy_eyeballs_timeout<D>(self, val: D) -> ClientBuilder
where D: Into<Option<Duration>>,

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.

Source

pub fn local_address<T>(self, addr: T) -> ClientBuilder
where T: Into<Option<IpAddr>>,

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();
Source

pub fn local_addresses<V4, V6>(self, ipv4: V4, ipv6: V6) -> ClientBuilder
where V4: Into<Option<Ipv4Addr>>, V6: Into<Option<Ipv6Addr>>,

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();
Source

pub fn interface<T>(self, interface: T) -> ClientBuilder
where T: Into<Cow<'static, str>>,

Available on Android or Fuchsia or illumos or iOS or Linux or macOS or Solaris or tvOS or visionOS or watchOS only.

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()?;
Source

pub fn identity(self, identity: Identity) -> ClientBuilder

Sets the identity to be used for client certificate authentication.

Source

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.

Source

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.

Source

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.

Source

pub fn tls_sni(self, tls_sni: bool) -> ClientBuilder

Configures the use of Server Name Indication (SNI) when connecting.

Defaults to true.

Source

pub fn keylog(self, keylog: KeyLog) -> ClientBuilder

Configures TLS key logging for the client.

Source

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.

Source

pub fn max_tls_version(self, version: TlsVersion) -> ClientBuilder

Set the maximum allowed TLS version for connections.

By default there’s no maximum.

Source

pub fn tls_info(self, tls_info: bool) -> ClientBuilder

Add TLS information as TlsInfo extension to responses.

§Optional

feature to be enabled.

Source

pub fn tls_options(self, options: TlsOptions) -> ClientBuilder

Sets the TLS options for the client.

Source

pub fn no_hickory_dns(self) -> ClientBuilder

Available on crate feature 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.

Source

pub fn resolve<D>(self, domain: D, addr: SocketAddr) -> ClientBuilder
where D: Into<Cow<'static, str>>,

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).

Source

pub fn resolve_to_addrs<D, A>(self, domain: D, addrs: A) -> ClientBuilder
where D: Into<Cow<'static, str>>, A: IntoIterator<Item = SocketAddr>,

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).

Source

pub fn dns_resolver<R>(self, resolver: R) -> ClientBuilder
where 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.

Source

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();
Source

pub fn recoveries(self, recoveries: Recoveries) -> ClientBuilder

Adds response recovery hooks to the client.

Source

pub fn on_request<F>(self, hook: F) -> ClientBuilder
where F: Fn(&mut Request<Body>) -> Result<(), Error> + Send + Sync + 'static,

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();
Source

pub fn on_response<F>(self, hook: F) -> ClientBuilder
where F: Fn(StatusCode, &HeaderMap) -> Result<(), Error> + Send + Sync + 'static,

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();
Source

pub fn on_status<F, Fut>(self, status: StatusCode, hook: F) -> ClientBuilder
where F: Fn(StatusRecoveryContext) -> Fut + Send + Sync + 'static, Fut: Future<Output = Result<Option<Request<Body>>, Error>> + Send + 'static,

Adds a status-based response recovery hook using a closure.

Source

pub fn layer<L>(self, layer: L) -> ClientBuilder
where 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();
Source

pub fn connector_layer<L>(self, layer: L) -> ClientBuilder
where L: Layer<BoxCloneSyncService<Unnameable, Conn, BoxError>> + Clone + Send + Sync + 'static, L::Service: Service<Unnameable, Response = Conn, Error = Box<dyn StdError + Send + Sync>> + Clone + Send + Sync + 'static, <L::Service as Service<Unnameable>>::Future: Send + 'static,

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();
Source

pub fn auth(self, auth: AuthMethod) -> ClientBuilder

Available on crate feature 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();
Source

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();
Source

pub fn emulation<P>(self, factory: P) -> ClientBuilder

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§

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts 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 more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts 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
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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<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