1use std::collections::HashMap;
2use std::time::Duration;
3
4use serde::Deserialize;
5use serde::Serialize;
6
7#[derive(Deserialize, Debug, Serialize, Clone)]
9pub struct Timeout(u64);
10
11impl Default for Timeout {
12 fn default() -> Self {
13 Timeout(30 * 1000)
14 }
15}
16
17impl From<Timeout> for Duration {
18 fn from(val: Timeout) -> Self {
19 Duration::from_millis(val.0)
20 }
21}
22
23impl From<u64> for Timeout {
24 fn from(v: u64) -> Self {
25 Self(v)
26 }
27}
28
29fn default_http_request_body() -> Option<Vec<u8>> {
30 None
31}
32
33#[derive(Debug, Clone, Deserialize, Serialize)]
46pub struct HttpRequest {
47 pub name: String,
49 pub method: String,
51 pub path: String,
53 #[serde(default)]
55 pub timeout: Timeout,
56 pub headers: HashMap<String, String>,
58 #[serde(default = "default_http_request_body")]
60 pub body: Option<Vec<u8>>,
61}
62
63impl From<(String, http::Method, String, Timeout)> for HttpRequest {
64 fn from((name, method, path, timeout): (String, http::Method, String, Timeout)) -> Self {
65 Self {
66 name,
67 method: method.to_string(),
68 path,
69 timeout,
70 headers: HashMap::new(),
71 body: None,
72 }
73 }
74}
75
76impl From<(&str, http::Method, &str, u64)> for HttpRequest {
77 fn from((name, method, url, timeout): (&str, http::Method, &str, u64)) -> Self {
78 (
79 name.to_owned(),
80 method,
81 url.to_owned(),
82 Timeout::from(timeout),
83 )
84 .into()
85 }
86}
87
88impl HttpRequest {
89 pub fn new<U>(
97 name: U,
98 method: http::Method,
99 path: U,
100 timeout: Timeout,
101 headers: &[(U, U)],
102 body: Option<Vec<u8>>,
103 ) -> Self
104 where
105 U: ToString,
106 {
107 Self {
108 name: name.to_string(),
109 method: method.to_string(),
110 path: path.to_string(),
111 timeout,
112 headers: headers
113 .iter()
114 .map(|(k, v)| (k.to_string(), v.to_string()))
115 .collect(),
116 body,
117 }
118 }
119
120 pub fn get<U>(
128 name: U,
129 url: U,
130 timeout: Timeout,
131 headers: &[(U, U)],
132 body: Option<Vec<u8>>,
133 ) -> Self
134 where
135 U: ToString,
136 {
137 Self::new(name, http::Method::GET, url, timeout, headers, body)
138 }
139}