http.rs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718
  1. // Copyright 2019-2022 Tauri Programme within The Commons Conservancy
  2. // SPDX-License-Identifier: Apache-2.0
  3. // SPDX-License-Identifier: MIT
  4. //! Types and functions related to HTTP request.
  5. use http::Method;
  6. pub use http::StatusCode;
  7. use serde::{Deserialize, Deserializer, Serialize};
  8. use serde_json::Value;
  9. use serde_repr::{Deserialize_repr, Serialize_repr};
  10. use url::Url;
  11. use std::{collections::HashMap, path::PathBuf, time::Duration};
  12. #[cfg(feature = "reqwest-client")]
  13. pub use reqwest::header;
  14. #[cfg(not(feature = "reqwest-client"))]
  15. pub use attohttpc::header;
  16. use header::{HeaderName, HeaderValue};
  17. #[derive(Deserialize)]
  18. #[serde(untagged)]
  19. enum SerdeDuration {
  20. Seconds(u64),
  21. Duration(Duration),
  22. }
  23. fn deserialize_duration<'de, D: Deserializer<'de>>(
  24. deserializer: D,
  25. ) -> Result<Option<Duration>, D::Error> {
  26. if let Some(duration) = Option::<SerdeDuration>::deserialize(deserializer)? {
  27. Ok(Some(match duration {
  28. SerdeDuration::Seconds(s) => Duration::from_secs(s),
  29. SerdeDuration::Duration(d) => d,
  30. }))
  31. } else {
  32. Ok(None)
  33. }
  34. }
  35. /// The builder of [`Client`].
  36. #[derive(Debug, Clone, Default, Deserialize)]
  37. #[serde(rename_all = "camelCase")]
  38. pub struct ClientBuilder {
  39. /// Max number of redirections to follow.
  40. pub max_redirections: Option<usize>,
  41. /// Connect timeout for the request.
  42. #[serde(deserialize_with = "deserialize_duration", default)]
  43. pub connect_timeout: Option<Duration>,
  44. }
  45. impl ClientBuilder {
  46. /// Creates a new client builder with the default options.
  47. pub fn new() -> Self {
  48. Default::default()
  49. }
  50. /// Sets the maximum number of redirections.
  51. #[must_use]
  52. pub fn max_redirections(mut self, max_redirections: usize) -> Self {
  53. self.max_redirections = Some(max_redirections);
  54. self
  55. }
  56. /// Sets the connection timeout.
  57. #[must_use]
  58. pub fn connect_timeout(mut self, connect_timeout: Duration) -> Self {
  59. self.connect_timeout.replace(connect_timeout);
  60. self
  61. }
  62. /// Builds the Client.
  63. #[cfg(not(feature = "reqwest-client"))]
  64. pub fn build(self) -> crate::api::Result<Client> {
  65. Ok(Client(self))
  66. }
  67. /// Builds the Client.
  68. #[cfg(feature = "reqwest-client")]
  69. pub fn build(self) -> crate::api::Result<Client> {
  70. let mut client_builder = reqwest::Client::builder();
  71. if let Some(max_redirections) = self.max_redirections {
  72. client_builder = client_builder.redirect(if max_redirections == 0 {
  73. reqwest::redirect::Policy::none()
  74. } else {
  75. reqwest::redirect::Policy::limited(max_redirections)
  76. });
  77. }
  78. if let Some(connect_timeout) = self.connect_timeout {
  79. client_builder = client_builder.connect_timeout(connect_timeout);
  80. }
  81. let client = client_builder.build()?;
  82. Ok(Client(client))
  83. }
  84. }
  85. /// The HTTP client based on [`reqwest`].
  86. #[cfg(feature = "reqwest-client")]
  87. #[derive(Debug, Clone)]
  88. pub struct Client(reqwest::Client);
  89. /// The HTTP client.
  90. #[cfg(not(feature = "reqwest-client"))]
  91. #[derive(Debug, Clone)]
  92. pub struct Client(ClientBuilder);
  93. #[cfg(not(feature = "reqwest-client"))]
  94. impl Client {
  95. /// Executes an HTTP request.
  96. ///
  97. /// # Examples
  98. ///
  99. /// ```rust,no_run
  100. /// use tauri::api::http::{ClientBuilder, HttpRequestBuilder, ResponseType};
  101. /// async fn run_request() {
  102. /// let client = ClientBuilder::new().build().unwrap();
  103. /// let response = client.send(
  104. /// HttpRequestBuilder::new("GET", "https://www.rust-lang.org")
  105. /// .unwrap()
  106. /// .response_type(ResponseType::Binary)
  107. /// ).await;
  108. /// if let Ok(response) = response {
  109. /// let bytes = response.bytes();
  110. /// }
  111. /// }
  112. /// ```
  113. pub async fn send(&self, request: HttpRequestBuilder) -> crate::api::Result<Response> {
  114. let method = Method::from_bytes(request.method.to_uppercase().as_bytes())?;
  115. let mut request_builder = attohttpc::RequestBuilder::try_new(method, &request.url)?;
  116. if let Some(query) = request.query {
  117. request_builder = request_builder.params(&query);
  118. }
  119. if let Some(headers) = &request.headers {
  120. for (name, value) in headers.0.iter() {
  121. request_builder = request_builder.header(name, value);
  122. }
  123. }
  124. if let Some(max_redirections) = self.0.max_redirections {
  125. if max_redirections == 0 {
  126. request_builder = request_builder.follow_redirects(false);
  127. } else {
  128. request_builder = request_builder.max_redirections(max_redirections as u32);
  129. }
  130. }
  131. if let Some(timeout) = request.timeout {
  132. request_builder = request_builder.timeout(timeout);
  133. }
  134. let response = if let Some(body) = request.body {
  135. match body {
  136. Body::Bytes(data) => request_builder.body(attohttpc::body::Bytes(data)).send()?,
  137. Body::Text(text) => request_builder.body(attohttpc::body::Bytes(text)).send()?,
  138. Body::Json(json) => request_builder.json(&json)?.send()?,
  139. Body::Form(form_body) => {
  140. #[allow(unused_variables)]
  141. fn send_form(
  142. request_builder: attohttpc::RequestBuilder,
  143. headers: &Option<HeaderMap>,
  144. form_body: FormBody,
  145. ) -> crate::api::Result<attohttpc::Response> {
  146. #[cfg(feature = "http-multipart")]
  147. if matches!(
  148. headers
  149. .as_ref()
  150. .and_then(|h| h.0.get("content-type"))
  151. .map(|v| v.as_bytes()),
  152. Some(b"multipart/form-data")
  153. ) {
  154. let mut multipart = attohttpc::MultipartBuilder::new();
  155. let mut byte_cache: HashMap<String, Vec<u8>> = Default::default();
  156. for (name, part) in &form_body.0 {
  157. if let FormPart::File { file, .. } = part {
  158. byte_cache.insert(name.to_string(), file.clone().try_into()?);
  159. }
  160. }
  161. for (name, part) in &form_body.0 {
  162. multipart = match part {
  163. FormPart::File {
  164. file,
  165. mime,
  166. file_name,
  167. } => {
  168. // safe to unwrap: always set by previous loop
  169. let mut file =
  170. attohttpc::MultipartFile::new(name, byte_cache.get(name).unwrap());
  171. if let Some(mime) = mime {
  172. file = file.with_type(mime)?;
  173. }
  174. if let Some(file_name) = file_name {
  175. file = file.with_filename(file_name);
  176. }
  177. multipart.with_file(file)
  178. }
  179. FormPart::Text(value) => multipart.with_text(name, value),
  180. };
  181. }
  182. return request_builder
  183. .body(multipart.build()?)
  184. .send()
  185. .map_err(Into::into);
  186. }
  187. let mut form = Vec::new();
  188. for (name, part) in form_body.0 {
  189. match part {
  190. FormPart::File { file, .. } => {
  191. let bytes: Vec<u8> = file.try_into()?;
  192. form.push((name, serde_json::to_string(&bytes)?))
  193. }
  194. FormPart::Text(value) => form.push((name, value)),
  195. }
  196. }
  197. request_builder.form(&form)?.send().map_err(Into::into)
  198. }
  199. send_form(request_builder, &request.headers, form_body)?
  200. }
  201. }
  202. } else {
  203. request_builder.send()?
  204. };
  205. Ok(Response(
  206. request.response_type.unwrap_or(ResponseType::Json),
  207. response,
  208. request.url,
  209. ))
  210. }
  211. }
  212. #[cfg(feature = "reqwest-client")]
  213. impl Client {
  214. /// Executes an HTTP request
  215. ///
  216. /// # Examples
  217. pub async fn send(&self, mut request: HttpRequestBuilder) -> crate::api::Result<Response> {
  218. let method = Method::from_bytes(request.method.to_uppercase().as_bytes())?;
  219. let mut request_builder = self.0.request(method, request.url.as_str());
  220. if let Some(query) = request.query {
  221. request_builder = request_builder.query(&query);
  222. }
  223. if let Some(timeout) = request.timeout {
  224. request_builder = request_builder.timeout(timeout);
  225. }
  226. if let Some(body) = request.body {
  227. request_builder = match body {
  228. Body::Bytes(data) => request_builder.body(bytes::Bytes::from(data)),
  229. Body::Text(text) => request_builder.body(bytes::Bytes::from(text)),
  230. Body::Json(json) => request_builder.json(&json),
  231. Body::Form(form_body) => {
  232. #[allow(unused_variables)]
  233. fn send_form(
  234. request_builder: reqwest::RequestBuilder,
  235. headers: &mut Option<HeaderMap>,
  236. form_body: FormBody,
  237. ) -> crate::api::Result<reqwest::RequestBuilder> {
  238. #[cfg(feature = "http-multipart")]
  239. if matches!(
  240. headers
  241. .as_ref()
  242. .and_then(|h| h.0.get("content-type"))
  243. .map(|v| v.as_bytes()),
  244. Some(b"multipart/form-data")
  245. ) {
  246. // the Content-Type header will be set by reqwest in the `.multipart` call
  247. headers.as_mut().map(|h| h.0.remove("content-type"));
  248. let mut multipart = reqwest::multipart::Form::new();
  249. for (name, part) in form_body.0 {
  250. let part = match part {
  251. FormPart::File {
  252. file,
  253. mime,
  254. file_name,
  255. } => {
  256. let bytes: Vec<u8> = file.try_into()?;
  257. let mut part = reqwest::multipart::Part::bytes(bytes);
  258. if let Some(mime) = mime {
  259. part = part.mime_str(&mime)?;
  260. }
  261. if let Some(file_name) = file_name {
  262. part = part.file_name(file_name);
  263. }
  264. part
  265. }
  266. FormPart::Text(value) => reqwest::multipart::Part::text(value),
  267. };
  268. multipart = multipart.part(name, part);
  269. }
  270. return Ok(request_builder.multipart(multipart));
  271. }
  272. let mut form = Vec::new();
  273. for (name, part) in form_body.0 {
  274. match part {
  275. FormPart::File { file, .. } => {
  276. let bytes: Vec<u8> = file.try_into()?;
  277. form.push((name, serde_json::to_string(&bytes)?))
  278. }
  279. FormPart::Text(value) => form.push((name, value)),
  280. }
  281. }
  282. Ok(request_builder.form(&form))
  283. }
  284. send_form(request_builder, &mut request.headers, form_body)?
  285. }
  286. };
  287. }
  288. if let Some(headers) = request.headers {
  289. request_builder = request_builder.headers(headers.0);
  290. }
  291. let http_request = request_builder.build()?;
  292. let response = self.0.execute(http_request).await?;
  293. Ok(Response(
  294. request.response_type.unwrap_or(ResponseType::Json),
  295. response,
  296. ))
  297. }
  298. }
  299. #[derive(Serialize_repr, Deserialize_repr, Clone, Debug)]
  300. #[repr(u16)]
  301. #[non_exhaustive]
  302. /// The HTTP response type.
  303. pub enum ResponseType {
  304. /// Read the response as JSON
  305. Json = 1,
  306. /// Read the response as text
  307. Text,
  308. /// Read the response as binary
  309. Binary,
  310. }
  311. /// A file path or contents.
  312. #[derive(Debug, Clone, Deserialize)]
  313. #[serde(untagged)]
  314. #[non_exhaustive]
  315. pub enum FilePart {
  316. /// File path.
  317. Path(PathBuf),
  318. /// File contents.
  319. Contents(Vec<u8>),
  320. }
  321. impl TryFrom<FilePart> for Vec<u8> {
  322. type Error = crate::api::Error;
  323. fn try_from(file: FilePart) -> crate::api::Result<Self> {
  324. let bytes = match file {
  325. FilePart::Path(path) => std::fs::read(path)?,
  326. FilePart::Contents(bytes) => bytes,
  327. };
  328. Ok(bytes)
  329. }
  330. }
  331. /// [`FormBody`] data types.
  332. #[derive(Debug, Deserialize)]
  333. #[serde(untagged)]
  334. #[non_exhaustive]
  335. pub enum FormPart {
  336. /// A string value.
  337. Text(String),
  338. /// A file value.
  339. #[serde(rename_all = "camelCase")]
  340. File {
  341. /// File path or content.
  342. file: FilePart,
  343. /// Mime type of this part.
  344. /// Only used when the `Content-Type` header is set to `multipart/form-data`.
  345. mime: Option<String>,
  346. /// File name.
  347. /// Only used when the `Content-Type` header is set to `multipart/form-data`.
  348. file_name: Option<String>,
  349. },
  350. }
  351. /// Form body definition.
  352. #[derive(Debug, Deserialize)]
  353. pub struct FormBody(pub(crate) HashMap<String, FormPart>);
  354. impl FormBody {
  355. /// Creates a new form body.
  356. pub fn new(data: HashMap<String, FormPart>) -> Self {
  357. Self(data)
  358. }
  359. }
  360. /// A body for the request.
  361. #[derive(Debug, Deserialize)]
  362. #[serde(tag = "type", content = "payload")]
  363. #[non_exhaustive]
  364. pub enum Body {
  365. /// A form body.
  366. Form(FormBody),
  367. /// A JSON body.
  368. Json(Value),
  369. /// A text string body.
  370. Text(String),
  371. /// A byte array body.
  372. Bytes(Vec<u8>),
  373. }
  374. /// A set of HTTP headers.
  375. #[derive(Debug, Default)]
  376. pub struct HeaderMap(header::HeaderMap);
  377. impl<'de> Deserialize<'de> for HeaderMap {
  378. fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  379. where
  380. D: Deserializer<'de>,
  381. {
  382. let map = HashMap::<String, String>::deserialize(deserializer)?;
  383. let mut headers = header::HeaderMap::default();
  384. for (key, value) in map {
  385. if let (Ok(key), Ok(value)) = (
  386. header::HeaderName::from_bytes(key.as_bytes()),
  387. header::HeaderValue::from_str(&value),
  388. ) {
  389. headers.insert(key, value);
  390. } else {
  391. return Err(serde::de::Error::custom(format!(
  392. "invalid header `{}` `{}`",
  393. key, value
  394. )));
  395. }
  396. }
  397. Ok(Self(headers))
  398. }
  399. }
  400. /// The builder for a HTTP request.
  401. ///
  402. /// # Examples
  403. /// ```rust,no_run
  404. /// use tauri::api::http::{HttpRequestBuilder, ResponseType, ClientBuilder};
  405. /// async fn run() {
  406. /// let client = ClientBuilder::new()
  407. /// .max_redirections(3)
  408. /// .build()
  409. /// .unwrap();
  410. /// let request = HttpRequestBuilder::new("GET", "http://example.com").unwrap()
  411. /// .response_type(ResponseType::Text);
  412. /// if let Ok(response) = client.send(request).await {
  413. /// println!("got response");
  414. /// } else {
  415. /// println!("Something Happened!");
  416. /// }
  417. /// }
  418. /// ```
  419. #[derive(Debug, Deserialize)]
  420. #[serde(rename_all = "camelCase")]
  421. pub struct HttpRequestBuilder {
  422. /// The request method (GET, POST, PUT, DELETE, PATCH, HEAD, OPTIONS, CONNECT or TRACE)
  423. pub method: String,
  424. /// The request URL
  425. pub url: Url,
  426. /// The request query params
  427. pub query: Option<HashMap<String, String>>,
  428. /// The request headers
  429. pub headers: Option<HeaderMap>,
  430. /// The request body
  431. pub body: Option<Body>,
  432. /// Timeout for the whole request
  433. #[serde(deserialize_with = "deserialize_duration", default)]
  434. pub timeout: Option<Duration>,
  435. /// The response type (defaults to Json)
  436. pub response_type: Option<ResponseType>,
  437. }
  438. impl HttpRequestBuilder {
  439. /// Initializes a new instance of the HttpRequestrequest_builder.
  440. pub fn new(method: impl Into<String>, url: impl AsRef<str>) -> crate::api::Result<Self> {
  441. Ok(Self {
  442. method: method.into(),
  443. url: Url::parse(url.as_ref())?,
  444. query: None,
  445. headers: None,
  446. body: None,
  447. timeout: None,
  448. response_type: None,
  449. })
  450. }
  451. /// Sets the request parameters.
  452. #[must_use]
  453. pub fn query(mut self, query: HashMap<String, String>) -> Self {
  454. self.query = Some(query);
  455. self
  456. }
  457. /// Adds a header.
  458. pub fn header<K, V>(mut self, key: K, value: V) -> crate::api::Result<Self>
  459. where
  460. HeaderName: TryFrom<K>,
  461. <HeaderName as TryFrom<K>>::Error: Into<http::Error>,
  462. HeaderValue: TryFrom<V>,
  463. <HeaderValue as TryFrom<V>>::Error: Into<http::Error>,
  464. {
  465. let key: Result<HeaderName, http::Error> = key.try_into().map_err(Into::into);
  466. let value: Result<HeaderValue, http::Error> = value.try_into().map_err(Into::into);
  467. self
  468. .headers
  469. .get_or_insert_with(Default::default)
  470. .0
  471. .insert(key?, value?);
  472. Ok(self)
  473. }
  474. /// Sets the request headers.
  475. #[must_use]
  476. pub fn headers(mut self, headers: header::HeaderMap) -> Self {
  477. self.headers.replace(HeaderMap(headers));
  478. self
  479. }
  480. /// Sets the request body.
  481. #[must_use]
  482. pub fn body(mut self, body: Body) -> Self {
  483. self.body = Some(body);
  484. self
  485. }
  486. /// Sets the general request timeout.
  487. #[must_use]
  488. pub fn timeout(mut self, timeout: Duration) -> Self {
  489. self.timeout.replace(timeout);
  490. self
  491. }
  492. /// Sets the type of the response. Interferes with the way we read the response.
  493. #[must_use]
  494. pub fn response_type(mut self, response_type: ResponseType) -> Self {
  495. self.response_type = Some(response_type);
  496. self
  497. }
  498. }
  499. /// The HTTP response.
  500. #[cfg(feature = "reqwest-client")]
  501. #[derive(Debug)]
  502. pub struct Response(ResponseType, reqwest::Response);
  503. /// The HTTP response.
  504. #[cfg(not(feature = "reqwest-client"))]
  505. #[derive(Debug)]
  506. pub struct Response(ResponseType, attohttpc::Response, Url);
  507. impl Response {
  508. /// Get the [`StatusCode`] of this Response.
  509. pub fn status(&self) -> StatusCode {
  510. self.1.status()
  511. }
  512. /// Get the headers of this Response.
  513. pub fn headers(&self) -> &header::HeaderMap {
  514. self.1.headers()
  515. }
  516. /// Reads the response as raw bytes.
  517. pub async fn bytes(self) -> crate::api::Result<RawResponse> {
  518. let status = self.status().as_u16();
  519. #[cfg(feature = "reqwest-client")]
  520. let data = self.1.bytes().await?.to_vec();
  521. #[cfg(not(feature = "reqwest-client"))]
  522. let data = self.1.bytes()?;
  523. Ok(RawResponse { status, data })
  524. }
  525. #[cfg(not(feature = "reqwest-client"))]
  526. #[allow(dead_code)]
  527. pub(crate) fn reader(self) -> attohttpc::ResponseReader {
  528. let (_, _, reader) = self.1.split();
  529. reader
  530. }
  531. // Convert the response into a Stream of [`bytes::Bytes`] from the body.
  532. //
  533. // # Examples
  534. //
  535. // ```no_run
  536. // use futures_util::StreamExt;
  537. //
  538. // # async fn run() -> Result<(), Box<dyn std::error::Error>> {
  539. // let client = tauri::api::http::ClientBuilder::new().build()?;
  540. // let mut stream = client.send(tauri::api::http::HttpRequestBuilder::new("GET", "http://httpbin.org/ip")?)
  541. // .await?
  542. // .bytes_stream();
  543. //
  544. // while let Some(item) = stream.next().await {
  545. // println!("Chunk: {:?}", item?);
  546. // }
  547. // # Ok(())
  548. // # }
  549. // ```
  550. #[cfg(feature = "reqwest-client")]
  551. #[allow(dead_code)]
  552. pub(crate) fn bytes_stream(
  553. self,
  554. ) -> impl futures_util::Stream<Item = crate::api::Result<bytes::Bytes>> {
  555. use futures_util::StreamExt;
  556. self.1.bytes_stream().map(|res| res.map_err(Into::into))
  557. }
  558. /// Reads the response.
  559. ///
  560. /// Note that the body is serialized to a [`Value`].
  561. pub async fn read(self) -> crate::api::Result<ResponseData> {
  562. #[cfg(feature = "reqwest-client")]
  563. let url = self.1.url().clone();
  564. #[cfg(not(feature = "reqwest-client"))]
  565. let url = self.2;
  566. let mut headers = HashMap::new();
  567. let mut raw_headers = HashMap::new();
  568. for (name, value) in self.1.headers() {
  569. headers.insert(
  570. name.as_str().to_string(),
  571. String::from_utf8(value.as_bytes().to_vec())?,
  572. );
  573. raw_headers.insert(
  574. name.as_str().to_string(),
  575. self
  576. .1
  577. .headers()
  578. .get_all(name)
  579. .into_iter()
  580. .map(|v| String::from_utf8(v.as_bytes().to_vec()).map_err(Into::into))
  581. .collect::<crate::api::Result<Vec<String>>>()?,
  582. );
  583. }
  584. let status = self.1.status().as_u16();
  585. #[cfg(feature = "reqwest-client")]
  586. let data = match self.0 {
  587. ResponseType::Json => self.1.json().await?,
  588. ResponseType::Text => Value::String(self.1.text().await?),
  589. ResponseType::Binary => serde_json::to_value(&self.1.bytes().await?)?,
  590. };
  591. #[cfg(not(feature = "reqwest-client"))]
  592. let data = match self.0 {
  593. ResponseType::Json => self.1.json()?,
  594. ResponseType::Text => Value::String(self.1.text()?),
  595. ResponseType::Binary => serde_json::to_value(self.1.bytes()?)?,
  596. };
  597. Ok(ResponseData {
  598. url,
  599. status,
  600. headers,
  601. raw_headers,
  602. data,
  603. })
  604. }
  605. }
  606. /// A response with raw bytes.
  607. #[non_exhaustive]
  608. #[derive(Debug)]
  609. pub struct RawResponse {
  610. /// Response status code.
  611. pub status: u16,
  612. /// Response bytes.
  613. pub data: Vec<u8>,
  614. }
  615. /// The response data.
  616. #[derive(Debug, Serialize)]
  617. #[serde(rename_all = "camelCase")]
  618. #[non_exhaustive]
  619. pub struct ResponseData {
  620. /// Response URL. Useful if it followed redirects.
  621. pub url: Url,
  622. /// Response status code.
  623. pub status: u16,
  624. /// Response headers.
  625. pub headers: HashMap<String, String>,
  626. /// Response raw headers.
  627. pub raw_headers: HashMap<String, Vec<String>>,
  628. /// Response data.
  629. pub data: Value,
  630. }
  631. #[cfg(test)]
  632. mod test {
  633. use super::ClientBuilder;
  634. use quickcheck::{Arbitrary, Gen};
  635. impl Arbitrary for ClientBuilder {
  636. fn arbitrary(g: &mut Gen) -> Self {
  637. Self {
  638. max_redirections: Option::arbitrary(g),
  639. connect_timeout: Option::arbitrary(g),
  640. }
  641. }
  642. }
  643. }