azure_core/http_client/
mod.rs

1#[cfg(not(any(feature = "enable_reqwest", feature = "enable_reqwest_rustls")))]
2mod noop;
3#[cfg(any(feature = "enable_reqwest", feature = "enable_reqwest_rustls"))]
4mod reqwest;
5
6#[cfg(not(any(feature = "enable_reqwest", feature = "enable_reqwest_rustls")))]
7use self::noop::new_noop_client;
8#[cfg(any(feature = "enable_reqwest", feature = "enable_reqwest_rustls"))]
9use self::reqwest::new_reqwest_client;
10use crate::error::ErrorKind;
11use async_trait::async_trait;
12use bytes::Bytes;
13use serde::{de::DeserializeOwned, Serialize};
14use std::sync::Arc;
15
16/// Construct a new `HttpClient`
17pub fn new_http_client() -> Arc<dyn HttpClient> {
18    #[cfg(any(feature = "enable_reqwest", feature = "enable_reqwest_rustls"))]
19    {
20        new_reqwest_client()
21    }
22    #[cfg(not(any(feature = "enable_reqwest", feature = "enable_reqwest_rustls")))]
23    {
24        new_noop_client()
25    }
26}
27
28/// An HTTP client which can send requests.
29#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
30#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
31pub trait HttpClient: Send + Sync + std::fmt::Debug {
32    /// Send out a request using `azure_core`'s types.
33    ///
34    /// It does not consume the request. Implementors are expected to clone the necessary parts
35    /// of the request and pass them to the underlying transport.
36    async fn execute_request(&self, request: &crate::Request) -> crate::Result<crate::Response>;
37
38    /// DEPRECATED: the status check will be responsibility of another policy (not the transport one).
39    /// Send out the request and collect the response body.
40    /// An error is returned if the status is not success.
41    async fn execute_request_check_status(
42        &self,
43        request: &crate::Request,
44    ) -> crate::Result<crate::CollectedResponse> {
45        let rsp = self.execute_request(request).await?;
46        let (status, headers, body) = rsp.deconstruct();
47        let body = body.collect().await?;
48
49        if status.is_success() {
50            Ok(crate::CollectedResponse::new(status, headers, body))
51        } else {
52            Err(ErrorKind::http_response_from_parts(status, &headers, &body).into_error())
53        }
54    }
55}
56
57/// Serialize a type to json.
58pub fn to_json<T>(value: &T) -> crate::Result<Bytes>
59where
60    T: ?Sized + Serialize,
61{
62    Ok(Bytes::from(serde_json::to_vec(value)?))
63}
64
65/// Reads the XML from bytes.
66pub fn from_json<S, T>(body: S) -> crate::Result<T>
67where
68    S: AsRef<[u8]>,
69    T: DeserializeOwned,
70{
71    serde_json::from_slice(body.as_ref()).map_err(Into::into)
72}