use std::sync::Arc;
use std::{collections::HashMap, fmt::Debug, time::Duration};
use http_client::{Config as HttpConfig, HttpClient};
use http_types::headers::{HeaderName, HeaderValues, ToHeaderValues};
use crate::http::Url;
use crate::Result;
#[non_exhaustive]
#[derive(Clone, Debug)]
pub struct Config {
pub base_url: Option<Url>,
pub headers: HashMap<HeaderName, HeaderValues>,
pub http_config: HttpConfig,
pub http_client: Option<Arc<dyn HttpClient>>,
}
impl Config {
pub fn new() -> Self {
Self::default()
}
}
impl Default for Config {
fn default() -> Self {
HttpConfig::default().into()
}
}
impl Config {
pub fn add_header(
mut self,
name: impl Into<HeaderName>,
values: impl ToHeaderValues,
) -> Result<Self> {
self.headers
.insert(name.into(), values.to_header_values()?.collect());
Ok(self)
}
pub fn set_base_url(mut self, base: Url) -> Self {
self.base_url = Some(base);
self
}
pub fn set_http_keep_alive(mut self, keep_alive: bool) -> Self {
self.http_config.http_keep_alive = keep_alive;
self
}
pub fn set_tcp_no_delay(mut self, no_delay: bool) -> Self {
self.http_config.tcp_no_delay = no_delay;
self
}
pub fn set_timeout(mut self, timeout: Option<Duration>) -> Self {
self.http_config.timeout = timeout;
self
}
pub fn set_max_connections_per_host(mut self, max_connections_per_host: usize) -> Self {
self.http_config.max_connections_per_host = max_connections_per_host;
self
}
pub fn set_http_client(mut self, http_client: impl HttpClient) -> Self {
self.http_client = Some(Arc::new(http_client));
self
}
#[cfg_attr(feature = "docs", doc(cfg(feature = "h1-client-rustls")))]
#[cfg(feature = "h1-client-rustls")]
pub fn set_tls_config(
mut self,
tls_config: Option<std::sync::Arc<rustls_crate::ClientConfig>>,
) -> Self {
self.http_config.tls_config = tls_config;
self
}
#[cfg_attr(feature = "docs", doc(cfg(feature = "h1-client")))]
#[cfg(feature = "h1-client")]
pub fn set_tls_config(
mut self,
tls_config: Option<std::sync::Arc<async_native_tls::TlsConnector>>,
) -> Self {
self.http_config.tls_config = tls_config;
self
}
}
impl AsRef<HttpConfig> for Config {
fn as_ref(&self) -> &HttpConfig {
&self.http_config
}
}
impl From<HttpConfig> for Config {
fn from(http_config: HttpConfig) -> Self {
Self {
base_url: None,
headers: HashMap::new(),
http_config,
http_client: None,
}
}
}