Skip to main content

axum/routing/
method_filter.rs

1use http::Method;
2use std::{
3    fmt,
4    fmt::{Debug, Formatter},
5};
6
7/// A filter that matches one or more HTTP methods.
8#[derive(Debug, Copy, Clone, PartialEq)]
9pub struct MethodFilter(u16);
10
11impl MethodFilter {
12    /// Match `CONNECT` requests.
13    ///
14    /// This is useful for implementing HTTP/2's [extended CONNECT method],
15    /// in which the `:protocol` pseudoheader is read
16    /// (using [`hyper::ext::Protocol`])
17    /// and the connection upgraded to a bidirectional byte stream
18    /// (using [`hyper::upgrade::on`]).
19    ///
20    /// As seen in the [HTTP Upgrade Token Registry],
21    /// common uses include WebSockets and proxying UDP or IP –
22    /// though note that when using [`WebSocketUpgrade`]
23    /// it's more useful to use [`any`](crate::routing::any)
24    /// as HTTP/1.1 WebSockets need to support `GET`.
25    ///
26    /// [extended CONNECT]: https://www.rfc-editor.org/rfc/rfc8441.html#section-4
27    /// [HTTP Upgrade Token Registry]: https://www.iana.org/assignments/http-upgrade-tokens/http-upgrade-tokens.xhtml
28    /// [`WebSocketUpgrade`]: crate::extract::WebSocketUpgrade
29    pub const CONNECT: Self = Self::from_bits(0b00_0000_0001);
30    /// Match `DELETE` requests.
31    pub const DELETE: Self = Self::from_bits(0b00_0000_0010);
32    /// Match `GET` requests.
33    pub const GET: Self = Self::from_bits(0b00_0000_0100);
34    /// Match `HEAD` requests.
35    pub const HEAD: Self = Self::from_bits(0b00_0000_1000);
36    /// Match `OPTIONS` requests.
37    pub const OPTIONS: Self = Self::from_bits(0b00_0001_0000);
38    /// Match `PATCH` requests.
39    pub const PATCH: Self = Self::from_bits(0b00_0010_0000);
40    /// Match `POST` requests.
41    pub const POST: Self = Self::from_bits(0b00_0100_0000);
42    /// Match `PUT` requests.
43    pub const PUT: Self = Self::from_bits(0b00_1000_0000);
44    /// Match `TRACE` requests.
45    pub const TRACE: Self = Self::from_bits(0b01_0000_0000);
46    /// Match `QUERY` requests.
47    pub const QUERY: Self = Self::from_bits(0b10_0000_0000);
48
49    const fn bits(self) -> u16 {
50        let bits = self;
51        bits.0
52    }
53
54    const fn from_bits(bits: u16) -> Self {
55        Self(bits)
56    }
57
58    pub(crate) const fn contains(self, other: Self) -> bool {
59        self.bits() & other.bits() == other.bits()
60    }
61
62    /// Performs the OR operation between the [`MethodFilter`] in `self` with `other`.
63    #[must_use]
64    pub const fn or(self, other: Self) -> Self {
65        Self(self.0 | other.0)
66    }
67}
68
69/// Error type used when converting a [`Method`] to a [`MethodFilter`] fails.
70#[derive(Debug)]
71pub struct NoMatchingMethodFilter {
72    method: Method,
73}
74
75impl NoMatchingMethodFilter {
76    /// Get the [`Method`] that couldn't be converted to a [`MethodFilter`].
77    pub fn method(&self) -> &Method {
78        &self.method
79    }
80}
81
82impl fmt::Display for NoMatchingMethodFilter {
83    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
84        write!(f, "no `MethodFilter` for `{}`", self.method.as_str())
85    }
86}
87
88impl std::error::Error for NoMatchingMethodFilter {}
89
90impl TryFrom<Method> for MethodFilter {
91    type Error = NoMatchingMethodFilter;
92
93    fn try_from(m: Method) -> Result<Self, NoMatchingMethodFilter> {
94        match m {
95            Method::CONNECT => Ok(Self::CONNECT),
96            Method::DELETE => Ok(Self::DELETE),
97            Method::GET => Ok(Self::GET),
98            Method::HEAD => Ok(Self::HEAD),
99            Method::OPTIONS => Ok(Self::OPTIONS),
100            Method::PATCH => Ok(Self::PATCH),
101            Method::POST => Ok(Self::POST),
102            Method::PUT => Ok(Self::PUT),
103            Method::TRACE => Ok(Self::TRACE),
104            Method::QUERY => Ok(Self::QUERY),
105            other => Err(NoMatchingMethodFilter { method: other }),
106        }
107    }
108}
109
110#[cfg(test)]
111mod tests {
112    use super::*;
113
114    #[test]
115    fn from_http_method() {
116        assert_eq!(
117            MethodFilter::try_from(Method::CONNECT).unwrap(),
118            MethodFilter::CONNECT
119        );
120
121        assert_eq!(
122            MethodFilter::try_from(Method::DELETE).unwrap(),
123            MethodFilter::DELETE
124        );
125
126        assert_eq!(
127            MethodFilter::try_from(Method::GET).unwrap(),
128            MethodFilter::GET
129        );
130
131        assert_eq!(
132            MethodFilter::try_from(Method::HEAD).unwrap(),
133            MethodFilter::HEAD
134        );
135
136        assert_eq!(
137            MethodFilter::try_from(Method::OPTIONS).unwrap(),
138            MethodFilter::OPTIONS
139        );
140
141        assert_eq!(
142            MethodFilter::try_from(Method::PATCH).unwrap(),
143            MethodFilter::PATCH
144        );
145
146        assert_eq!(
147            MethodFilter::try_from(Method::POST).unwrap(),
148            MethodFilter::POST
149        );
150
151        assert_eq!(
152            MethodFilter::try_from(Method::PUT).unwrap(),
153            MethodFilter::PUT
154        );
155
156        assert_eq!(
157            MethodFilter::try_from(Method::TRACE).unwrap(),
158            MethodFilter::TRACE
159        );
160
161        assert_eq!(
162            MethodFilter::try_from(Method::QUERY).unwrap(),
163            MethodFilter::QUERY
164        );
165
166        assert!(
167            MethodFilter::try_from(http::Method::from_bytes(b"CUSTOM").unwrap())
168                .unwrap_err()
169                .to_string()
170                .contains("CUSTOM")
171        );
172    }
173}