gitignore_template_generator/http_client/
impls.rs

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