soph_http/support/
http.rs1use crate::{config, error::Error, traits::ErrorTrait, Http, HttpResult};
2use reqwest_middleware::{ClientBuilder, ClientWithMiddleware};
3use soph_config::support::config;
4use std::{net::IpAddr, str::FromStr, time::Duration};
5
6impl Http {
7 pub fn new() -> HttpResult<Self> {
8 let config = config().parse::<config::Http>()?;
9
10 let mut reqwest_client = reqwest::Client::builder();
11
12 if let Some(timeout) = config.timeout {
13 reqwest_client = reqwest_client.timeout(Duration::from_millis(timeout));
14 }
15
16 if let Some(pool_idle_timeout) = config.pool_idle_timeout {
17 reqwest_client = reqwest_client.pool_idle_timeout(Duration::from_millis(pool_idle_timeout));
18 }
19
20 if let Some(pool_max_idle_per_host) = config.pool_max_idle_per_host {
21 reqwest_client = reqwest_client.pool_max_idle_per_host(pool_max_idle_per_host);
22 }
23
24 if let Some(local_address) = config.local_address {
25 reqwest_client = reqwest_client.local_address(IpAddr::from_str(&local_address).ok());
26 }
27
28 if let Some(tcp_keepalive) = config.tcp_keepalive {
29 reqwest_client = reqwest_client.tcp_keepalive(Duration::from_millis(tcp_keepalive));
30 }
31
32 #[allow(unused_mut)]
33 let mut client = ClientBuilder::new(reqwest_client.build().map_err(Error::wrap)?);
34
35 #[cfg(feature = "tracing")]
36 {
37 client = client.with(reqwest_tracing::TracingMiddleware::default());
38 }
39
40 #[cfg(feature = "retry")]
41 {
42 client = client.with(reqwest_retry::RetryTransientMiddleware::new_with_policy(
43 reqwest_retry::policies::ExponentialBackoff::builder().build_with_max_retries(config.max_retry),
44 ));
45 }
46
47 Ok(Self { client: client.build() })
48 }
49}
50
51impl std::ops::Deref for Http {
52 type Target = ClientWithMiddleware;
53
54 fn deref(&self) -> &Self::Target {
55 &self.client
56 }
57}