Skip to main content

serenade_http/
method.rs

1//! HTTP request methods.
2
3use std::fmt::{Display, Formatter};
4use std::str::FromStr;
5
6use crate::HttpError;
7
8/// HTTP method on [`crate::Request`].
9#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
10pub enum Method {
11    /// GET.
12    Get,
13    /// HEAD.
14    Head,
15    /// POST.
16    Post,
17    /// PUT.
18    Put,
19    /// PATCH.
20    Patch,
21    /// DELETE.
22    Delete,
23    /// OPTIONS.
24    Options,
25}
26
27impl Method {
28    /// Uppercase token used on the wire.
29    #[must_use]
30    pub const fn as_str(self) -> &'static str {
31        match self {
32            Self::Get => "GET",
33            Self::Head => "HEAD",
34            Self::Post => "POST",
35            Self::Put => "PUT",
36            Self::Patch => "PATCH",
37            Self::Delete => "DELETE",
38            Self::Options => "OPTIONS",
39        }
40    }
41}
42
43impl Display for Method {
44    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
45        f.write_str(self.as_str())
46    }
47}
48
49impl FromStr for Method {
50    type Err = HttpError;
51
52    fn from_str(value: &str) -> Result<Self, Self::Err> {
53        match value.to_ascii_uppercase().as_str() {
54            "GET" => Ok(Self::Get),
55            "HEAD" => Ok(Self::Head),
56            "POST" => Ok(Self::Post),
57            "PUT" => Ok(Self::Put),
58            "PATCH" => Ok(Self::Patch),
59            "DELETE" => Ok(Self::Delete),
60            "OPTIONS" => Ok(Self::Options),
61            _ => Err(HttpError::status(
62                405,
63                format!("unsupported method `{value}`"),
64            )),
65        }
66    }
67}