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
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
use crate::web::{Method, Request, Response};
use std::collections::HashMap;
use web_sys::Url;
pub struct Conn {
pub host: String,
pub method: Method,
pub port: u16,
pub scheme: String,
pub path: String,
pub query_string: String,
pub req_body: String,
pub req_headers: HashMap<String, String>,
pub cf: HashMap<String, String>,
pub resp_body: String,
pub resp_headers: HashMap<String, String>,
pub status: u16,
pub assigns: HashMap<String, String>,
pub halted: bool,
}
pub fn create_conn(request: Request) -> Conn {
let method: Method = get_method(request.method);
let url = Url::new(request.url.as_str()).unwrap();
let port: u16 = url.port().parse::<u16>().unwrap_or(80);
let host = url.host();
Conn {
method,
port,
host,
scheme: url.protocol(),
assigns: HashMap::new(),
cf: request.cf,
halted: false,
path: url.pathname(),
query_string: url.search(),
req_body: request.body,
req_headers: request.headers,
resp_body: String::new(),
resp_headers: HashMap::new(),
status: 200,
}
}
pub fn conn_to_response(conn: Conn) -> Response {
return Response {
status: conn.status,
headers: conn.resp_headers,
body: conn.resp_body,
};
}
pub fn html(conn: Conn, content: &str) -> Conn {
let mut headers = conn.resp_headers;
headers.insert("Content-Type".to_string(), "text/html".to_string());
return Conn {
resp_headers: headers,
resp_body: content.to_string(),
status: 200,
..conn
};
}
pub fn json(conn: Conn, content: &str) -> Conn {
let mut headers = conn.resp_headers;
headers.insert("Content-Type".to_string(), "application/json".to_string());
return Conn {
resp_headers: headers,
resp_body: content.to_string(),
status: 200,
..conn
};
}
pub fn xml(conn: Conn, content: &str) -> Conn {
let mut headers = conn.resp_headers;
headers.insert("Content-Type".to_string(), "application/xml".to_string());
return Conn {
resp_headers: headers,
resp_body: content.to_string(),
status: 200,
..conn
};
}
fn get_method(method: String) -> Method {
match method.to_uppercase().as_str() {
"GET" => Method::Get,
"HEAD" => Method::Head,
"POST" => Method::Post,
"PUT" => Method::Put,
"DELETE" => Method::Delete,
"CONNECT" => Method::Connect,
"OPTIONS" => Method::Options,
"TRACE" => Method::Trace,
"PATCH" => Method::Patch,
_ => Method::Get,
}
}