1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
use http::{
header::{HeaderMap, HeaderValue, CONTENT_TYPE},
method::Method,
status::StatusCode,
};
use super::{HttpRequest, HttpResponse};
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("HTTP error")]
Http(#[from] http::Error),
#[error("IO error")]
IO(#[from] std::io::Error),
#[error("Other error: {}", _0)]
Other(String),
#[error("ureq request failed")]
Ureq(#[from] Box<ureq::Error>),
}
pub fn http_client(request: HttpRequest) -> Result<HttpResponse, Error> {
let mut req = if let Method::POST = request.method {
ureq::post(&request.url.to_string())
} else {
ureq::get(&request.url.to_string())
};
for (name, value) in request.headers {
if let Some(name) = name {
req = req.set(
&name.to_string(),
value.to_str().map_err(|_| {
Error::Other(format!(
"invalid {} header value {:?}",
name,
value.as_bytes()
))
})?,
);
}
}
let response = if let Method::POST = request.method {
req.send(&*request.body)
} else {
req.call()
}
.map_err(Box::new)?;
Ok(HttpResponse {
status_code: StatusCode::from_u16(response.status())
.map_err(|err| Error::Http(err.into()))?,
headers: vec![(
CONTENT_TYPE,
HeaderValue::from_str(response.content_type())
.map_err(|err| Error::Http(err.into()))?,
)]
.into_iter()
.collect::<HeaderMap>(),
body: response.into_string()?.as_bytes().into(),
})
}