luct-client 0.2.2

Client library to fetch and validate certificate transparency logs
Documentation
//! Implementation of the [`Client`] trait using [`reqwest`]

use crate::{Client, ClientError};
use reqwest::Response;
use std::sync::Arc;
use url::Url;

#[derive(Debug, Clone, Default)]
pub struct ReqwestClient {
    client: reqwest::Client,
}

impl ReqwestClient {
    pub fn new(agent: &str) -> Self {
        #[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
        let _ = rustls_rustcrypto::provider().install_default();

        Self {
            client: reqwest::Client::builder()
                .user_agent(agent)
                .build()
                .expect("Failed to initialize reqwest client"),
        }
    }
}

impl Client for ReqwestClient {
    async fn get(
        &self,
        url: &Url,
        params: &[(&str, &str)],
    ) -> Result<(u16, Arc<String>), ClientError> {
        let response = self.request(url, params).await?;
        let status = response.status().as_u16();
        let data = response
            .text()
            .await
            .map_err(|err| ClientError::ConnectionErrorStd(Arc::new(err)))?;

        Ok((status, Arc::new(data)))
    }

    async fn get_bin(
        &self,
        url: &Url,
        params: &[(&str, &str)],
    ) -> Result<(u16, Arc<Vec<u8>>), ClientError> {
        let response = self.request(url, params).await?;
        let status = response.status().as_u16();
        let data = response
            .bytes()
            .await
            .map_err(|err| ClientError::ConnectionErrorStd(Arc::new(err)))?;

        Ok((status, Arc::new(data.to_vec())))
    }
}

impl ReqwestClient {
    async fn request(&self, url: &Url, params: &[(&str, &str)]) -> Result<Response, ClientError> {
        self.client
            .get(url.clone())
            .query(params)
            .send()
            .await
            .map_err(|err| ClientError::ConnectionErrorStd(Arc::new(err)))
    }
}