luct_client/impls/
reqwest.rs1use crate::{Client, ClientError};
4use reqwest::Response;
5use std::sync::Arc;
6use url::Url;
7
8#[derive(Debug, Clone, Default)]
9pub struct ReqwestClient {
10 client: reqwest::Client,
11}
12
13impl ReqwestClient {
14 pub fn new(agent: &str) -> Self {
15 #[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
16 rustls_rustcrypto::provider()
17 .install_default()
18 .expect("Failed to initialize rustcrypto");
19
20 Self {
21 client: reqwest::Client::builder()
22 .user_agent(agent)
23 .build()
24 .expect("Failed to initialize reqwest client"),
25 }
26 }
27}
28
29impl Client for ReqwestClient {
30 #[tracing::instrument(level = "trace")]
31 async fn get(
32 &self,
33 url: &Url,
34 params: &[(&str, &str)],
35 ) -> Result<(u16, Arc<String>), ClientError> {
36 let response = self.request(url, params).await?;
37 let status = response.status().as_u16();
38 let data = response
39 .text()
40 .await
41 .map_err(|err| ClientError::ConnectionErrorStd(Arc::new(err)))?;
42
43 Ok((status, Arc::new(data)))
44 }
45
46 #[tracing::instrument(level = "trace")]
47 async fn get_bin(
48 &self,
49 url: &Url,
50 params: &[(&str, &str)],
51 ) -> Result<(u16, Arc<Vec<u8>>), ClientError> {
52 let response = self.request(url, params).await?;
53 let status = response.status().as_u16();
54 let data = response
55 .bytes()
56 .await
57 .map_err(|err| ClientError::ConnectionErrorStd(Arc::new(err)))?;
58
59 Ok((status, Arc::new(data.to_vec())))
60 }
61}
62
63impl ReqwestClient {
64 async fn request(&self, url: &Url, params: &[(&str, &str)]) -> Result<Response, ClientError> {
65 self.client
66 .get(url.clone())
67 .query(params)
68 .send()
69 .await
70 .map_err(|err| ClientError::ConnectionErrorStd(Arc::new(err)))
71 }
72}