Skip to main content

g_server/http/
method.rs

1use std::{borrow::Cow, fmt};
2
3/// An HTTP request method.
4#[derive(Debug, Clone, PartialEq, Eq, Hash)]
5pub struct Method(Cow<'static, str>);
6
7impl Method {
8    pub const GET: Self = Self(Cow::Borrowed("GET"));
9    pub const POST: Self = Self(Cow::Borrowed("POST"));
10    pub const PUT: Self = Self(Cow::Borrowed("PUT"));
11    pub const PATCH: Self = Self(Cow::Borrowed("PATCH"));
12    pub const DELETE: Self = Self(Cow::Borrowed("DELETE"));
13    pub const HEAD: Self = Self(Cow::Borrowed("HEAD"));
14    pub const OPTIONS: Self = Self(Cow::Borrowed("OPTIONS"));
15    pub const CONNECT: Self = Self(Cow::Borrowed("CONNECT"));
16    pub const TRACE: Self = Self(Cow::Borrowed("TRACE"));
17
18    /// Creates a custom HTTP method.
19    pub fn new(method: impl Into<String>) -> Self {
20        Self(Cow::Owned(method.into()))
21    }
22
23    /// Returns the method as a string slice.
24    pub fn as_str(&self) -> &str {
25        &self.0
26    }
27
28    pub fn is_get(&self) -> bool {
29        self == &Self::GET
30    }
31
32    pub fn is_post(&self) -> bool {
33        self == &Self::POST
34    }
35
36    pub fn is_put(&self) -> bool {
37        self == &Self::PUT
38    }
39
40    pub fn is_patch(&self) -> bool {
41        self == &Self::PATCH
42    }
43
44    pub fn is_delete(&self) -> bool {
45        self == &Self::DELETE
46    }
47
48    pub fn is_head(&self) -> bool {
49        self == &Self::HEAD
50    }
51
52    pub fn is_options(&self) -> bool {
53        self == &Self::OPTIONS
54    }
55
56    pub fn is_connect(&self) -> bool {
57        self == &Self::CONNECT
58    }
59
60    pub fn is_trace(&self) -> bool {
61        self == &Self::TRACE
62    }
63}
64
65impl fmt::Display for Method {
66    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
67        f.write_str(self.as_str())
68    }
69}
70
71impl From<String> for Method {
72    fn from(method: String) -> Self {
73        Self::new(method)
74    }
75}
76
77impl From<&str> for Method {
78    fn from(method: &str) -> Self {
79        Self::new(method)
80    }
81}