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
use crate::{
common::{
command::{Command, RequestMethod},
connection_common::build_headers,
},
error::{RemoteConnectionError, WebDriverError, WebDriverResult},
};
#[derive(Debug)]
pub struct RemoteConnectionSync {
url: String,
client: reqwest::blocking::Client,
}
impl RemoteConnectionSync {
pub fn new(remote_server_addr: &str) -> Result<Self, RemoteConnectionError> {
let headers = build_headers(remote_server_addr)?;
Ok(RemoteConnectionSync {
url: remote_server_addr.trim_end_matches('/').to_owned(),
client: reqwest::blocking::Client::builder()
.default_headers(headers)
.build()?,
})
}
pub fn execute(&self, command: Command) -> WebDriverResult<serde_json::Value> {
let request_data = command.format_request();
let url = self.url.clone() + &request_data.url;
let mut request = match request_data.method {
RequestMethod::Get => self.client.get(&url),
RequestMethod::Post => self.client.post(&url),
RequestMethod::Delete => self.client.delete(&url),
};
if let Some(x) = request_data.body {
request = request.json(&x);
}
let resp = request
.send()
.map_err(|e| WebDriverError::RequestFailed(e.to_string()))?;
match resp.status().as_u16() {
200..=399 => Ok(resp
.json()
.map_err(|e| WebDriverError::JsonError(e.to_string()))?),
400..=599 => {
let status = resp.status().as_u16();
let body: serde_json::Value = resp
.json()
.map_err(|e| WebDriverError::JsonError(e.to_string()))?;
Err(WebDriverError::parse(status, body))
}
_ => Err(WebDriverError::RequestFailed(format!(
"Unknown response: {:?}",
resp.json()
.map_err(|e| WebDriverError::JsonError(e.to_string()))?
))),
}
}
}