use reqwest::Client;
use std::time::Duration;
use crate::config::OnesOidcConfig;
const DEFAULT_TIMEOUT_SECS: u64 = 3;
#[derive(Debug, Clone)]
pub struct HttpClientConfig {
pub timeout: Duration,
pub user_agent: Option<String>,
}
impl Default for HttpClientConfig {
fn default() -> Self {
Self {
timeout: Duration::from_secs(DEFAULT_TIMEOUT_SECS),
user_agent: Some(format!("ones-oidc/{}", env!("CARGO_PKG_VERSION"))),
}
}
}
impl HttpClientConfig {
#[allow(dead_code)]
pub fn with_timeout(timeout: Duration) -> Self {
Self {
timeout,
..Default::default()
}
}
#[allow(dead_code)]
pub fn with_user_agent(user_agent: String) -> Self {
Self {
user_agent: Some(user_agent),
..Default::default()
}
}
pub fn build_client(&self) -> Result<Client, reqwest::Error> {
let mut builder = Client::builder()
.timeout(self.timeout);
if let Some(ref user_agent) = self.user_agent {
builder = builder.user_agent(user_agent);
}
builder.build()
}
}
pub fn default_client() -> Result<Client, reqwest::Error> {
HttpClientConfig::default().build_client()
}
#[allow(dead_code)]
pub fn client_from_config(config: &OnesOidcConfig) -> Result<Client, reqwest::Error> {
let mut builder = Client::builder()
.timeout(config.http_timeout);
if let Some(ref user_agent) = config.user_agent {
builder = builder.user_agent(user_agent);
}
builder.build()
}
#[allow(dead_code)]
pub fn client_with_timeout(timeout: Duration) -> Result<Client, reqwest::Error> {
HttpClientConfig::with_timeout(timeout).build_client()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default_config() {
let config = HttpClientConfig::default();
assert_eq!(config.timeout, Duration::from_secs(DEFAULT_TIMEOUT_SECS));
assert!(config.user_agent.is_some());
}
#[test]
fn test_custom_timeout() {
let timeout = Duration::from_secs(10);
let config = HttpClientConfig::with_timeout(timeout);
assert_eq!(config.timeout, timeout);
}
#[test]
fn test_build_client() {
let config = HttpClientConfig::default();
let client = config.build_client();
assert!(client.is_ok());
}
}