monoio_http_client/
response.rs

1use bytes::Bytes;
2use http::{Extensions, HeaderMap, HeaderValue, StatusCode, Version};
3use monoio_http::common::body::{BodyExt, HttpBody};
4
5pub struct ClientResponse {
6    /// The response's status
7    status: StatusCode,
8    /// The response's version
9    version: Version,
10    /// The response's headers
11    headers: HeaderMap<HeaderValue>,
12    /// The response's extensions
13    extensions: Extensions,
14    /// Payload
15    body: HttpBody,
16}
17
18impl ClientResponse {
19    pub fn new(inner: http::Response<HttpBody>) -> Self {
20        let (head, body) = inner.into_parts();
21        Self {
22            status: head.status,
23            version: head.version,
24            headers: head.headers,
25            extensions: head.extensions,
26            body,
27        }
28    }
29
30    /// Get the `StatusCode` of this `Response`.
31    #[inline]
32    pub fn status(&self) -> StatusCode {
33        self.status
34    }
35
36    /// Get the HTTP `Version` of this `Response`.
37    #[inline]
38    pub fn version(&self) -> Version {
39        self.version
40    }
41
42    /// Get the `Headers` of this `Response`.
43    #[inline]
44    pub fn headers(&self) -> &HeaderMap {
45        &self.headers
46    }
47
48    /// Get a mutable reference to the `Headers` of this `Response`.
49    #[inline]
50    pub fn headers_mut(&mut self) -> &mut HeaderMap {
51        &mut self.headers
52    }
53
54    /// Returns a reference to the associated extensions.
55    pub fn extensions(&self) -> &http::Extensions {
56        &self.extensions
57    }
58
59    /// Returns a mutable reference to the associated extensions.
60    pub fn extensions_mut(&mut self) -> &mut http::Extensions {
61        &mut self.extensions
62    }
63
64    /// Get the full response body as `Bytes`.
65    pub async fn bytes(self) -> crate::Result<Bytes> {
66        let body = self.body;
67        body.bytes().await.map_err(Into::into)
68    }
69
70    /// Get raw body(Payload).
71    pub fn raw_body(self) -> HttpBody {
72        self.body
73    }
74
75    /// Try to deserialize the response body as JSON.
76    // Note: using from_reader to read discontinuous data pays more
77    // than using from_slice. So here we read the entire content into
78    // a Bytes and call from_slice.
79    pub async fn json<T: serde::de::DeserializeOwned>(self) -> crate::Result<T> {
80        let bytes = self.body.bytes().await?;
81        let d = serde_json::from_slice(&bytes)?;
82        Ok(d)
83    }
84}