Skip to main content

apigate_core/
parts_ctx.rs

1use crate::error::ApigateError;
2use http::header::{HeaderName, HeaderValue};
3use http::request::Parts;
4
5pub struct PartsCtx<'a> {
6    service: &'static str,
7    route_path: &'static str,
8    parts: &'a mut Parts,
9}
10
11impl<'a> PartsCtx<'a> {
12    pub fn new(service: &'static str, route_path: &'static str, parts: &'a mut Parts) -> Self {
13        Self {
14            service,
15            route_path,
16            parts,
17        }
18    }
19
20    pub fn service(&self) -> &'static str {
21        self.service
22    }
23
24    pub fn route_path(&self) -> &'static str {
25        self.route_path
26    }
27
28    pub fn method(&self) -> &http::Method {
29        &self.parts.method
30    }
31
32    pub fn uri(&self) -> &http::Uri {
33        &self.parts.uri
34    }
35
36    pub fn uri_mut(&mut self) -> &mut http::Uri {
37        &mut self.parts.uri
38    }
39
40    pub fn headers(&self) -> &http::HeaderMap {
41        &self.parts.headers
42    }
43
44    pub fn headers_mut(&mut self) -> &mut http::HeaderMap {
45        &mut self.parts.headers
46    }
47
48    pub fn header(&self, name: &str) -> Option<&str> {
49        self.parts.headers.get(name).and_then(|v| v.to_str().ok())
50    }
51
52    pub fn set_header(
53        &mut self,
54        name: impl TryInto<HeaderName>,
55        value: impl TryInto<HeaderValue>,
56    ) -> Result<(), ApigateError> {
57        let name = name
58            .try_into()
59            .map_err(|_| ApigateError::bad_request("invalid header name"))?;
60        let value = value
61            .try_into()
62            .map_err(|_| ApigateError::bad_request("invalid header value"))?;
63
64        self.parts.headers.insert(name, value);
65        Ok(())
66    }
67
68    pub fn set_header_if_absent(
69        &mut self,
70        name: impl TryInto<HeaderName>,
71        value: impl TryInto<HeaderValue>,
72    ) -> Result<(), ApigateError> {
73        let name = name
74            .try_into()
75            .map_err(|_| ApigateError::bad_request("invalid header name"))?;
76        if self.parts.headers.contains_key(&name) {
77            return Ok(());
78        }
79
80        let value = value
81            .try_into()
82            .map_err(|_| ApigateError::bad_request("invalid header value"))?;
83
84        self.parts.headers.insert(name, value);
85        Ok(())
86    }
87
88    pub fn remove_header(&mut self, name: &str) {
89        self.parts.headers.remove(name);
90    }
91
92    pub fn extensions(&self) -> &http::Extensions {
93        &self.parts.extensions
94    }
95
96    pub fn extensions_mut(&mut self) -> &mut http::Extensions {
97        &mut self.parts.extensions
98    }
99}