use std::fmt::Display;
#[derive(Clone, Debug, PartialEq, Eq, Ord, PartialOrd, Hash)]
pub enum HttpMethod {
Get,
Head,
Post,
Put,
Delete,
Options,
Trace,
Patch,
Custom(String),
}
impl PartialEq<HttpMethod> for &HttpMethod {
fn eq(&self, other: &HttpMethod) -> bool {
match self {
HttpMethod::Get => matches!(other, HttpMethod::Get),
HttpMethod::Head => matches!(other, HttpMethod::Head),
HttpMethod::Post => matches!(other, HttpMethod::Post),
HttpMethod::Put => matches!(other, HttpMethod::Put),
HttpMethod::Delete => matches!(other, HttpMethod::Delete),
HttpMethod::Options => matches!(other, HttpMethod::Options),
HttpMethod::Trace => matches!(other, HttpMethod::Trace),
HttpMethod::Patch => matches!(other, HttpMethod::Patch),
HttpMethod::Custom(name) => name.eq(other.as_str()),
}
}
}
static WELL_KNOWN: &[HttpMethod] = &[
HttpMethod::Get,
HttpMethod::Head,
HttpMethod::Post,
HttpMethod::Put,
HttpMethod::Delete,
HttpMethod::Options,
HttpMethod::Trace,
HttpMethod::Patch,
];
impl HttpMethod {
pub fn from(name: &str) -> Self {
match name {
"GET" => Self::Get,
"HEAD" => Self::Head,
"POST" => Self::Post,
"PUT" => Self::Put,
"DELETE" => Self::Delete,
"OPTIONS" => Self::Options,
"TRACE" => Self::Trace,
"PATCH" => Self::Patch,
_ => Self::Custom(name.to_ascii_uppercase()),
}
}
#[must_use]
pub fn well_known() -> &'static [HttpMethod] {
WELL_KNOWN
}
pub fn is_well_known(&self) -> bool {
!matches!(self, Self::Custom(_))
}
pub fn is_custom(&self) -> bool {
matches!(self, Self::Custom(_))
}
#[must_use]
pub fn well_known_str(&self) -> Option<&'static str> {
Some(match self {
HttpMethod::Get => "GET",
HttpMethod::Head => "HEAD",
HttpMethod::Post => "POST",
HttpMethod::Put => "PUT",
HttpMethod::Delete => "DELETE",
HttpMethod::Options => "OPTIONS",
HttpMethod::Trace => "TRACE",
HttpMethod::Patch => "PATCH",
HttpMethod::Custom(_) => return None,
})
}
pub fn as_str(&self) -> &str {
match self {
HttpMethod::Get => "GET",
HttpMethod::Head => "HEAD",
HttpMethod::Post => "POST",
HttpMethod::Put => "PUT",
HttpMethod::Delete => "DELETE",
HttpMethod::Options => "OPTIONS",
HttpMethod::Trace => "TRACE",
HttpMethod::Patch => "PATCH",
HttpMethod::Custom(meth) => meth.as_str(),
}
}
pub fn is_likely_to_have_request_body(&self) -> bool {
matches!(self, HttpMethod::Post | HttpMethod::Put | HttpMethod::Patch | HttpMethod::Custom(_))
}
}
impl Display for HttpMethod {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}