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