workflow_http/
native.rs

1use crate::error::Error;
2use crate::result::Result;
3
4pub async fn get(url: impl Into<String>) -> Result<String> {
5    Request::new(url).get().await
6}
7
8pub async fn get_bytes(url: impl Into<String>) -> Result<Vec<u8>> {
9    Request::new(url).get_bytes().await
10}
11
12pub async fn get_json<T: serde::de::DeserializeOwned + 'static>(
13    url: impl Into<String>,
14) -> Result<T> {
15    Request::new(url).get_json().await
16}
17
18pub struct Request {
19    pub url: String,
20    pub user_agent: Option<String>,
21}
22
23impl Request {
24    pub fn new(url: impl Into<String>) -> Self {
25        Self {
26            url: url.into(),
27            user_agent: None,
28        }
29    }
30
31    pub fn with_user_agent(mut self, user_agent: impl Into<String>) -> Self {
32        self.user_agent = Some(user_agent.into());
33        self
34    }
35
36    pub async fn get(self) -> Result<String> {
37        let mut req = reqwest::Client::new().get(&self.url);
38        if let Some(user_agent) = self.user_agent {
39            req = req.header("User-Agent", user_agent);
40        }
41        let resp = req.send().await?;
42        let status = resp.status();
43        let text = resp.text().await?;
44        if status.is_success() {
45            Ok(text)
46        } else {
47            Err(Error::Custom(format!("{}: {}", status, text)))
48        }
49    }
50
51    pub async fn get_bytes(self) -> Result<Vec<u8>> {
52        let mut req = reqwest::Client::new().get(&self.url);
53        if let Some(user_agent) = self.user_agent {
54            req = req.header("User-Agent", user_agent);
55        }
56        let resp = req.send().await?;
57        let status = resp.status();
58        let bytes = resp.bytes().await?;
59        if status.is_success() {
60            Ok(bytes.to_vec())
61        } else {
62            Err(Error::Custom(format!("{}: {:?}", status, bytes)))
63        }
64    }
65
66    pub async fn get_json<T: serde::de::DeserializeOwned + 'static>(self) -> Result<T> {
67        let mut req = reqwest::Client::new().get(&self.url);
68        if let Some(user_agent) = self.user_agent {
69            req = req.header("User-Agent", user_agent);
70        }
71        let resp = req.send().await?;
72        let status = resp.status();
73        let text = resp.text().await?;
74        if status.is_success() {
75            Ok(serde_json::from_str(&text)?)
76        } else {
77            Err(Error::Custom(format!("{}: {}", status, text)))
78        }
79    }
80}