graph_core/http/
response_builder_ext.rs1use 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
13pub trait HttpResponseBuilderExt {
17 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}