graph_core/http/
response_builder_ext.rs

1use url::Url;
2
3#[derive(Debug, Clone, PartialEq)]
4pub(crate) struct HttpExtUrl(pub Url);
5
6#[allow(dead_code)]
7#[derive(Debug, Clone, PartialEq)]
8pub(crate) struct HttpExtSerdeJsonValue(pub serde_json::Value);
9
10#[derive(Debug, Clone, PartialEq)]
11pub(crate) struct HttpExtVecU8(pub Vec<u8>);
12
13/// Extension trait for http::response::Builder objects
14///
15/// Allows the user to add a `Url` to the http::Response
16pub trait HttpResponseBuilderExt {
17    /// A builder method for the `http::response::Builder` type that allows the user to add a `Url`
18    /// to the `http::Response`
19    fn url(self, url: Url) -> Self;
20    fn json(self, value: &serde_json::Value) -> Self;
21}
22
23impl HttpResponseBuilderExt for http::response::Builder {
24    fn url(self, url: Url) -> Self {
25        self.extension(HttpExtUrl(url))
26    }
27
28    fn json(self, value: &serde_json::Value) -> Self {
29        if let Ok(value) = serde_json::to_vec(value) {
30            return self.extension(HttpExtVecU8(value));
31        }
32
33        self
34    }
35}
36
37pub trait HttpResponseExt {
38    fn url(&self) -> Option<Url>;
39    fn json(&self) -> Option<serde_json::Value>;
40}
41
42impl<T> HttpResponseExt for http::Response<T> {
43    fn url(&self) -> Option<Url> {
44        self.extensions()
45            .get::<HttpExtUrl>()
46            .map(|url| url.clone().0)
47    }
48
49    fn json(&self) -> Option<serde_json::Value> {
50        self.extensions()
51            .get::<HttpExtVecU8>()
52            .and_then(|value| serde_json::from_slice(value.0.as_slice()).ok())
53    }
54}