1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
|
use itertools::Itertools;
use std::collections::HashMap;
pub enum StatusCode {
// 2xx Success
Ok,
// 4xx Client Error
BadRequest,
NotFound,
}
type Route = String;
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum Method {
Get(Route),
Post(Route),
Put(Route),
}
pub fn get(route: &str) -> Method {
Method::Get(route.to_string())
}
pub fn post(route: &str) -> Method {
Method::Post(route.to_string())
}
pub fn put(route: &str) -> Method {
Method::Put(route.to_string())
}
impl From<StatusCode> for String {
fn from(val: StatusCode) -> Self {
use StatusCode::*;
match val {
Ok => "200 OK".to_string(),
BadRequest => "400 Bad Request".to_string(),
NotFound => "404 Not Found".to_string(),
}
}
}
impl From<Method> for String {
fn from(val: Method) -> Self {
use Method::*;
match val {
Get(route) => "GET ".to_string() + &route,
Post(route) => "POST ".to_string() + &route,
Put(route) => "PUT ".to_string() + &route,
}
}
}
impl From<&Method> for String {
fn from(val: &Method) -> Self {
use Method::*;
match val {
Get(route) => "GET ".to_string() + &route,
Post(route) => "POST ".to_string() + &route,
Put(route) => "PUT ".to_string() + &route,
}
}
}
#[derive(Debug, Clone)]
pub struct Headers(pub HashMap<String, String>);
impl From<Vec<String>> for Headers {
fn from(value: Vec<String>) -> Self {
let mut header_map = HashMap::new();
for header in value.iter().filter(|val| !val.is_empty()) {
let (key, val) = header
.split_once(": ")
.expect("Should be splitable by :<space>");
header_map.insert(key.to_string(), val.to_string());
}
Headers(header_map)
}
}
impl From<&[&str]> for Headers {
fn from(value: &[&str]) -> Self {
let mut header_map = HashMap::new();
for header in value.iter().filter(|val| !val.is_empty()) {
let (key, val) = header
.split_once(": ")
.expect("Should be splitable by :<space>");
header_map.insert(key.to_string(), val.to_string());
}
Headers(header_map)
}
}
impl From<String> for Method {
fn from(val: String) -> Self {
use Method::*;
let request_line = val.split(' ').collect_vec();
let (method, route) = (request_line[0], request_line[1]);
match method {
"GET" => Get(route.to_string()),
"POST" => Post(route.to_string()),
_ => {
eprintln!("{method} Not Supported Yet");
unreachable!()
}
}
}
}
impl From<&str> for Method {
fn from(val: &str) -> Self {
use Method::*;
let request_line = val.split(' ').collect_vec();
let (method, route) = (request_line[0], request_line[1]);
match method {
"GET" => Get(route.to_string()),
"POST" => Post(route.to_string()),
_ => {
eprintln!("{method} Not Supported Yet");
unreachable!()
}
}
}
}
|