joist 1.0.0

A backend framework for Rust: routing, middleware, JSON, config and plugins, with no third-party dependencies.
Documentation
use std::fmt;

/// An HTTP request method.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Method {
    Get,
    Head,
    Post,
    Put,
    Patch,
    Delete,
    Options,
    Trace,
    Connect,
}

impl Method {
    /// Parse a method token. Returns `None` for anything not in RFC 9110,
    /// because an unrecognised method is a client error rather than something
    /// to guess at.
    pub fn parse(token: &str) -> Option<Method> {
        Some(match token {
            "GET" => Method::Get,
            "HEAD" => Method::Head,
            "POST" => Method::Post,
            "PUT" => Method::Put,
            "PATCH" => Method::Patch,
            "DELETE" => Method::Delete,
            "OPTIONS" => Method::Options,
            "TRACE" => Method::Trace,
            "CONNECT" => Method::Connect,
            _ => return None,
        })
    }

    pub fn as_str(self) -> &'static str {
        match self {
            Method::Get => "GET",
            Method::Head => "HEAD",
            Method::Post => "POST",
            Method::Put => "PUT",
            Method::Patch => "PATCH",
            Method::Delete => "DELETE",
            Method::Options => "OPTIONS",
            Method::Trace => "TRACE",
            Method::Connect => "CONNECT",
        }
    }

    /// Whether the method usually carries a request body.
    pub fn expects_body(self) -> bool {
        matches!(self, Method::Post | Method::Put | Method::Patch)
    }
}

impl fmt::Display for Method {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parses_known_methods() {
        assert_eq!(Method::parse("GET"), Some(Method::Get));
        assert_eq!(Method::parse("DELETE"), Some(Method::Delete));
    }

    #[test]
    fn rejects_unknown_and_lowercase() {
        // HTTP methods are case-sensitive, so "get" is not GET.
        assert_eq!(Method::parse("get"), None);
        assert_eq!(Method::parse("BREW"), None);
    }

    #[test]
    fn round_trips() {
        let all = [
            Method::Get,
            Method::Head,
            Method::Post,
            Method::Put,
            Method::Patch,
            Method::Delete,
            Method::Options,
            Method::Trace,
            Method::Connect,
        ];
        for m in all {
            assert_eq!(Method::parse(m.as_str()), Some(m));
        }
    }
}