thirtyfour_sync/http/
reqwest_sync.rs

1use std::fmt::Debug;
2
3use crate::http::connection_sync::{HttpClientCreateParams, WebDriverHttpClientSync};
4use crate::{
5    common::connection_common::reqwest_support::build_reqwest_headers,
6    error::{WebDriverError, WebDriverResult},
7};
8use std::time::Duration;
9use thirtyfour::{RequestData, RequestMethod};
10
11/// Synchronous connection to the remote WebDriver server.
12#[derive(Debug)]
13pub struct ReqwestDriverSync {
14    url: String,
15    client: reqwest::blocking::Client,
16    timeout: Duration,
17}
18
19impl WebDriverHttpClientSync for ReqwestDriverSync {
20    fn create(params: HttpClientCreateParams) -> WebDriverResult<Self> {
21        let url = params.server_url.trim_end_matches('/').to_owned();
22        let headers = build_reqwest_headers(&url)?;
23        Ok(ReqwestDriverSync {
24            url,
25            client: reqwest::blocking::Client::builder().default_headers(headers).build()?,
26            timeout: params.timeout.unwrap_or_else(|| Duration::from_secs(120)),
27        })
28    }
29
30    /// Set the HTTP client request timeout.
31    fn set_request_timeout(&mut self, timeout: Duration) {
32        self.timeout = timeout;
33    }
34
35    /// Execute the specified command and return the data as serde_json::Value.
36    fn execute(&self, request_data: RequestData) -> WebDriverResult<serde_json::Value> {
37        let url = self.url.clone() + &request_data.url;
38        let mut request = match request_data.method {
39            RequestMethod::Get => self.client.get(&url),
40            RequestMethod::Post => self.client.post(&url),
41            RequestMethod::Delete => self.client.delete(&url),
42        };
43        request = request.timeout(self.timeout);
44
45        if let Some(x) = request_data.body {
46            request = request.json(&x);
47        }
48
49        let resp = request.send()?;
50
51        match resp.status().as_u16() {
52            200..=399 => Ok(resp.json()?),
53            400..=599 => {
54                let status = resp.status().as_u16();
55                Err(WebDriverError::parse(status, resp.text()?))
56            }
57            _ => unreachable!(),
58        }
59    }
60}