gitignore_template_generator/http_client/
impls.rs

1use crate::{ExitKind, ProgramExit, constant, http_client::api::HttpClient};
2
3/// Http client implementation relying on [`ureq`].
4#[derive(Default)]
5pub struct UreqClient {
6    /// The base url of the HTTP server to reach.
7    ///
8    /// Used as base url when calling [`UreqClient::get`] method.
9    pub server_url: String,
10}
11
12/// Http client implementation to mock a response.
13pub struct MockClient {
14    /// The mocked response to be returned when calling [`MockClient::get`]
15    /// method.
16    pub response: Result<String, ProgramExit>,
17}
18
19impl HttpClient for UreqClient {
20    /// Make a GET HTTP call using a [`ureq`] client.
21    ///
22    /// The server base url (i.e. https://localhost:8080) should be provided
23    /// as part of [`UreqClient::server_url] field.
24    ///
25    /// See [`HttpClient::get`] for more infos.
26    fn get(&self, url: &str) -> Result<String, ProgramExit> {
27        let full_url = format!("{}{url}", self.server_url);
28        let result = ureq::get(full_url).call();
29
30        match result {
31            Ok(mut response) => match response.body_mut().read_to_string() {
32                Ok(body) => Ok(body),
33                Err(_error) => Err(ProgramExit {
34                    message: String::from(
35                        constant::error_messages::BODY_PARSING_ISSUE,
36                    ),
37                    exit_status: constant::exit_status::BODY_PARSING_ISSUE,
38                    styled_message: None,
39                    kind: ExitKind::Error,
40                }),
41            },
42            Err(error) => Err(ProgramExit {
43                message: constant::error_messages::API_CALL_FAILURE
44                    .replace("{error}", &error.to_string()),
45                exit_status: constant::exit_status::GENERIC,
46                styled_message: None,
47                kind: ExitKind::Error,
48            }),
49        }
50    }
51}
52
53impl HttpClient for MockClient {
54    /// Returns the result linked to this instance.
55    ///
56    /// The given `_url` will not be used, simply a clone of linked
57    /// result will be returned.
58    fn get(&self, _url: &str) -> Result<String, ProgramExit> {
59        self.response.clone()
60    }
61}