Skip to main content

agent_line/tools/
http.rs

1use std::time::Duration;
2
3use crate::agent::StepError;
4use ureq::{self, Agent};
5
6/// Send a GET request and return the response body as a string.
7pub fn http_get(url: &str) -> Result<String, StepError> {
8    let config = Agent::config_builder()
9        .timeout_global(Some(Duration::from_secs(5)))
10        .build();
11
12    let agent: Agent = config.into();
13
14    let body: String = agent
15        .get(url)
16        .header("User-Agent", "agent-line")
17        .call()?
18        .body_mut()
19        .read_to_string()?;
20
21    Ok(body)
22}
23
24/// Send a POST request with a string body and return the response body.
25pub fn http_post(url: &str, body: &str) -> Result<String, StepError> {
26    let config = Agent::config_builder()
27        .timeout_global(Some(Duration::from_secs(5)))
28        .build();
29
30    let agent: Agent = config.into();
31
32    let response = agent
33        .post(url)
34        .header("User-Agent", "agent-line")
35        .send(body)?
36        .body_mut()
37        .read_to_string()?;
38
39    Ok(response)
40}
41
42/// Send a POST request with a JSON body and return the response body.
43pub fn http_post_json(url: &str, body: &serde_json::Value) -> Result<String, StepError> {
44    let config = Agent::config_builder()
45        .timeout_global(Some(Duration::from_secs(5)))
46        .build();
47
48    let agent: Agent = config.into();
49
50    let response = agent
51        .post(url)
52        .header("User-Agent", "agent-line")
53        .send_json(body)?
54        .body_mut()
55        .read_to_string()?;
56
57    Ok(response)
58}
59
60#[cfg(test)]
61mod tests {
62    use super::*;
63
64    #[test]
65    fn test_http_post_bad_url_returns_error() {
66        let result = http_post("http://localhost:1/nope", "body content");
67        assert!(result.is_err());
68    }
69
70    #[test]
71    fn test_http_post_json_bad_url_returns_error() {
72        let body = serde_json::json!({"key": "value"});
73        let result = http_post_json("http://localhost:1/nope", &body);
74        assert!(result.is_err());
75    }
76}