Skip to main content

a3s_boot/http/
method.rs

1use crate::BootError;
2use std::fmt;
3use std::str::FromStr;
4
5/// HTTP method understood by Boot route definitions.
6#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
7pub enum HttpMethod {
8    /// Route-definition wildcard that matches every standard HTTP method.
9    All,
10    Get,
11    Post,
12    Put,
13    Patch,
14    Delete,
15    Options,
16    Head,
17}
18
19impl HttpMethod {
20    pub const STANDARD: [Self; 7] = [
21        Self::Get,
22        Self::Post,
23        Self::Put,
24        Self::Patch,
25        Self::Delete,
26        Self::Options,
27        Self::Head,
28    ];
29
30    pub fn as_str(self) -> &'static str {
31        match self {
32            Self::All => "ALL",
33            Self::Get => "GET",
34            Self::Post => "POST",
35            Self::Put => "PUT",
36            Self::Patch => "PATCH",
37            Self::Delete => "DELETE",
38            Self::Options => "OPTIONS",
39            Self::Head => "HEAD",
40        }
41    }
42
43    pub fn standard_methods() -> &'static [Self] {
44        &Self::STANDARD
45    }
46
47    pub fn is_wildcard(self) -> bool {
48        matches!(self, Self::All)
49    }
50
51    pub fn is_standard(self) -> bool {
52        !self.is_wildcard()
53    }
54
55    pub fn matches(self, request_method: Self) -> bool {
56        self == request_method || (self.is_wildcard() && request_method.is_standard())
57    }
58}
59
60impl fmt::Display for HttpMethod {
61    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
62        f.write_str(self.as_str())
63    }
64}
65
66impl FromStr for HttpMethod {
67    type Err = BootError;
68
69    fn from_str(method: &str) -> std::result::Result<Self, Self::Err> {
70        match method {
71            "GET" => Ok(Self::Get),
72            "POST" => Ok(Self::Post),
73            "PUT" => Ok(Self::Put),
74            "PATCH" => Ok(Self::Patch),
75            "DELETE" => Ok(Self::Delete),
76            "OPTIONS" => Ok(Self::Options),
77            "HEAD" => Ok(Self::Head),
78            method => Err(BootError::MethodNotAllowed(method.to_string())),
79        }
80    }
81}