Skip to main content

go_http/
method.rs

1// SPDX-License-Identifier: Apache-2.0
2
3pub const GET: &str = "GET";
4pub const HEAD: &str = "HEAD";
5pub const POST: &str = "POST";
6pub const PUT: &str = "PUT";
7pub const PATCH: &str = "PATCH";
8pub const DELETE: &str = "DELETE";
9pub const CONNECT: &str = "CONNECT";
10pub const OPTIONS: &str = "OPTIONS";
11pub const TRACE: &str = "TRACE";
12
13/// Returns true if `m` is a valid HTTP method token (RFC 7230 §3.2.6).
14pub fn is_valid(m: &str) -> bool {
15    !m.is_empty()
16        && m.bytes().all(|b| {
17            matches!(b,
18                b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9'
19                | b'!' | b'#' | b'$' | b'%' | b'&' | b'\'' | b'*' | b'+'
20                | b'-' | b'.' | b'^' | b'_' | b'`' | b'|' | b'~'
21            )
22        })
23}
24
25#[cfg(test)]
26mod tests {
27    use super::*;
28
29    #[test]
30    fn valid_methods() {
31        for m in &[GET, HEAD, POST, PUT, PATCH, DELETE, CONNECT, OPTIONS, TRACE] {
32            assert!(is_valid(m), "{m} should be valid");
33        }
34    }
35
36    #[test]
37    fn invalid_methods() {
38        assert!(!is_valid(""));
39        assert!(!is_valid("GET EXTRA"));
40        assert!(!is_valid("GÉT"));
41    }
42}