1use std::str::FromStr;
2
3#[derive(Debug, PartialEq, Eq, Clone, Copy)]
5pub enum HttpMethod {
6 GET,
7 HEAD
8}
9
10impl FromStr for HttpMethod {
11 type Err = &'static str;
12
13 fn from_str(s: &str) -> Result<Self, Self::Err> {
15 match s {
16 "GET" => Ok(HttpMethod::GET),
17 "HEAD" => Ok(HttpMethod::HEAD),
18 _ => Err("HTTP method not supported."),
19 }
20 }
21}
22
23#[derive(Debug, PartialEq, Eq, Clone, Copy)]
25pub enum HttpVersion {
26 Http1_0,
27 Http1_1,
28}
29
30impl FromStr for HttpVersion {
31 type Err = &'static str;
32
33 fn from_str(s: &str) -> Result<Self, Self::Err> {
35 match s {
36 "HTTP/1.0" => Ok(HttpVersion::Http1_0),
37 "HTTP/1.1" => Ok(HttpVersion::Http1_1),
38 _ => Err("Unsupported HTTP version"),
39 }
40 }
41}
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
45pub enum StatusCode {
46 Ok,
48 BadRequest,
50 Forbidden,
52 NotFound,
54 MethodNotAllowed,
56 InternalServerError,
58 NotImplemented,
60 HttpVersionNotSupported,
62}
63
64impl StatusCode {
65
66 pub fn code(&self) -> u16 {
68 match self {
69 StatusCode::Ok => 200,
70 StatusCode::BadRequest => 400,
71 StatusCode::Forbidden => 403,
72 StatusCode::NotFound => 404,
73 StatusCode::MethodNotAllowed => 405,
74 StatusCode::InternalServerError => 500,
75 StatusCode::NotImplemented => 501,
76 StatusCode::HttpVersionNotSupported => 505,
77 }
78 }
79
80 pub fn reason(&self) -> &'static str {
82 match self {
83 StatusCode::Ok => "OK",
84 StatusCode::BadRequest => "Bad Request",
85 StatusCode::Forbidden => "Forbidden",
86 StatusCode::NotFound => "Not Found",
87 StatusCode::MethodNotAllowed => "Method Not Allowed",
88 StatusCode::InternalServerError => "Internal Server Error",
89 StatusCode::NotImplemented => "Not Implemented",
90 StatusCode::HttpVersionNotSupported => "HTTP Version Not Supported",
91 }
92 }
93}
94
95#[cfg(test)]
96mod tests {
97 use super::*;
98
99 #[test]
100 fn test_parse_http_method() {
101 assert_eq!("GET".parse(), Ok(HttpMethod::GET));
102 assert_eq!("HEAD".parse(), Ok(HttpMethod::HEAD));
103 assert!("POST".parse::<HttpMethod>().is_err());
104 }
105
106 #[test]
107 fn test_parse_http_version() {
108 assert_eq!("HTTP/1.0".parse(), Ok(HttpVersion::Http1_0));
109 assert_eq!("HTTP/1.1".parse(), Ok(HttpVersion::Http1_1));
110 assert!("HTTP/2.0".parse::<HttpVersion>().is_err());
111 }
112
113 #[test]
114 fn test_status_code_and_reason() {
115 assert_eq!(StatusCode::Ok.code(), 200);
116 assert_eq!(StatusCode::NotFound.reason(), "Not Found");
117 assert_eq!(StatusCode::InternalServerError.code(), 500);
118 }
119}