miku_http_util/
response.rs

1//! HTTP response utilities
2
3use bytes::Bytes;
4use http::response::Parts;
5
6#[derive(Debug, Clone)]
7/// Response (Extended)
8pub struct ResponseExt<B = Bytes> {
9    /// HTTP response parts (see [`http::response::Parts`])
10    pub response_parts: Parts,
11
12    /// Body bytes
13    pub body: B,
14}
15
16impl ResponseExt {
17    #[cfg(feature = "feat-response-ext-json")]
18    /// Convert the body to a JSON value
19    ///
20    /// If the body is not valid JSON, the original response is returned as an
21    /// error.
22    pub fn json<T>(self) -> Result<ResponseExt<T>, Self>
23    where
24        T: for<'a> serde::Deserialize<'a>,
25    {
26        match serde_json::from_slice(&self.body) {
27            Ok(body) => Ok(ResponseExt {
28                response_parts: self.response_parts,
29                body,
30            }),
31            Err(e) => {
32                #[cfg(feature = "feat-tracing")]
33                tracing::error!("Failed to parse JSON: {e:?}");
34                Err(self)
35            }
36        }
37    }
38}