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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
use std::io::Read;
use failure::Error;
use reqwest::{Client, StatusCode};
use reqwest::Response as HttpResponse;
use reqwest::header::{ContentType, UserAgent};
use super::{Connector, ConnectorError, Status, USER_AGENT};
pub struct ReqwestConnector {
http: Client,
url: String,
}
impl Connector for ReqwestConnector {
fn open(mut connector_url: &str) -> Result<Self, Error> {
if !connector_url.starts_with("http://") && !connector_url.starts_with("https://") {
Err(ConnectorError::InvalidURL)?;
}
if connector_url.ends_with('/') {
connector_url = &connector_url[..connector_url.len() - 1];
}
Ok(Self {
http: Client::new(),
url: connector_url.to_owned(),
})
}
fn status(&self) -> Result<Status, Error> {
let http_response = self.get("/connector/status")?;
let status = String::from_utf8(http_response)?;
Status::parse(&status)
}
fn send_command(&self, cmd: Vec<u8>) -> Result<Vec<u8>, Error> {
self.post("/connector/api", cmd)
}
}
impl ReqwestConnector {
fn get(&self, path: &str) -> Result<Vec<u8>, Error> {
let mut response = self.http
.get(&self.url_for(path)?)
.header(UserAgent::new(USER_AGENT))
.send()?;
handle_http_response(&mut response)
}
fn post(&self, path: &str, body: Vec<u8>) -> Result<Vec<u8>, Error> {
let mut response = self.http
.post(&self.url_for(path)?)
.header(ContentType::octet_stream())
.header(UserAgent::new(USER_AGENT))
.body(body)
.send()?;
handle_http_response(&mut response)
}
fn url_for(&self, path: &str) -> Result<String, Error> {
if !path.starts_with('/') {
Err(ConnectorError::InvalidURL)?;
}
Ok(format!("{}{}", self.url, path))
}
}
fn handle_http_response(response: &mut HttpResponse) -> Result<Vec<u8>, Error> {
if response.status() != StatusCode::Ok {
fail!(
ConnectorError::ResponseError,
"unexpected HTTP status: {}",
response.status()
);
}
let mut body = Vec::new();
response.read_to_end(&mut body)?;
Ok(body)
}