wikipedia_wasm/
http.rs

1#![allow(async_fn_in_trait)]
2pub use failure::Error;
3
4pub trait HttpClient {
5    fn user_agent(&mut self, user_agent: String);
6    async fn get<'a, I>(&self, base_url: &str, args: I) -> Result<String, Error>
7    where
8        I: Iterator<Item = (&'a str, &'a str)>;
9}
10
11
12#[cfg(feature = "http-client")]
13pub mod default {
14    use failure::err_msg;
15    use reqwest;
16
17    use super::{Error, HttpClient};
18
19    pub struct Client {
20        user_agent: String,
21    }
22
23    impl Default for Client {
24        fn default() -> Self {
25            Client {
26                user_agent: "".to_owned(),
27            }
28        }
29    }
30
31    impl HttpClient for Client {
32        fn user_agent(&mut self, user_agent: String) {
33            self.user_agent = user_agent;
34        }
35
36        async fn get<'a, I>(&self, base_url: &str, args: I) -> Result<String, Error>
37        where
38            I: Iterator<Item = (&'a str, &'a str)>,
39        {
40            // Add origin=* so I can do a bit of trunk serve.
41            let mut args = args.collect::<Vec<(&'a str, &'a str)>>();
42            args.insert(0, ("origin", "*"));
43
44            let url = reqwest::Url::parse_with_params(base_url, args)?;
45
46            let client = reqwest::Client::new();
47            let response = client
48                .get(url)
49                .header(reqwest::header::USER_AGENT, self.user_agent.clone())
50                .send().await?;
51
52            ensure!(response.status().is_success(), err_msg("Bad status"));
53
54            let response_str = response.text().await?;
55
56            Ok(response_str)
57        }
58    }
59}