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
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
use self::{http_method::HttpMethod, request_line::RequestLine};
use std::{
collections::HashMap,
fmt::{Debug, Display, Formatter, Result as fResult},
net::{IpAddr, Ipv4Addr, SocketAddr},
};
pub use body::RequestBody;
pub mod body;
pub mod builder;
pub mod http_method;
pub(crate) mod parser;
mod request_line;
#[doc = include_str!("../docs/core/request.md")]
#[derive(Clone)]
pub struct Request {
request: RequestLine,
headers: HashMap<String, String>,
queries: HashMap<String, String>,
params: HashMap<String, String>,
body: RequestBody,
peer_addr: SocketAddr,
}
impl Request {
/// Returns the reference of the Request headers as a HashMap
///
/// # Example
///
/// ```rust
/// use krustie::{ request::Request, response::Response};
///
/// fn get(request: &Request, response: &mut Response) {
/// let headers = request.get_headers();
/// let content_type = headers.get("content-type");
/// }
/// ```
pub fn get_headers(&self) -> &HashMap<String, String> {
&self.headers
}
/// Returns the value of the requested header
///
/// # Example
///
/// ```rust
/// use krustie::{ request::Request, response::Response};
///
/// fn get(request: &Request, response: &mut Response) {
/// let content_type = request.get_header("content-type");
/// }
/// ```
pub fn get_header(&self, key: &str) -> Option<&str> {
self.headers.get(key).map(|v| v.as_str())
}
/// Returns the body of the HTTP request
///
/// The body can be of type `Text`, `Json`, `Form` or `None`
///
/// # Example
///
/// ```rust
/// use krustie::{ Request, Response, request::RequestBody };
///
/// fn get(request: &Request, response: &mut Response) {
/// match request.get_body() {
/// RequestBody::Text(body) => {
/// // Do something with the body
/// },
/// RequestBody::Json(json) => {
/// // Do something with the json
/// },
/// _ => {
/// // Do something else
/// }
/// }
/// }
/// ```
pub fn get_body(&self) -> &RequestBody {
&self.body
}
/// Returns the peer address of the HTTP request
///
/// The peer address is the ip address of the client that made the request
///
/// # Example
///
/// ```rust
/// use krustie::{ Request, Response };
/// use std::net::SocketAddr;
///
/// fn get(request: &Request, response: &mut Response) {
/// let peer_addr: &SocketAddr = request.get_peer_addr();
/// }
/// ```
pub fn get_peer_addr(&self) -> &SocketAddr {
&self.peer_addr
}
/// Returns the queries of the HTTP request as a HashMap
///
/// | The path of the HTTP request | Value |
/// | -- | -- |
/// | `/hello` | `[]` |
/// | `/hello?planet=earth` | `[{ "planet": "earth" }]` |
/// | `/hello?planet=earth&moon=luna` | `[{ "planet": "earth" }, { "moon": "luna"}]` |
///
/// # Example
///
/// ```rust
/// use krustie::{ Request, Response };
///
/// fn get(request: &Request, response: &mut Response) {
/// let queries = request
/// .get_query_params()
/// .iter()
/// .map(|(k, v)| format!("{}: {}", k, v))
/// .collect::<Vec<String>>();
/// }
/// ```
pub fn get_query_params(&self) -> &HashMap<String, String> {
&self.queries
}
/// Returns the query parameter of the HTTP request
///
/// | The path of the HTTP request | get_query_param(key: &str) | Returns |
/// | -- | -- | -- |
/// | `/hello?planet=earth` | `get_query_param("planet")` | Some("earth") |
/// | `/hello?planet=earth` | `get_query_param("moon")` | None |
/// | `/hello?planet=earth&moon=luna` | `get_query_param("moon")` | Some("luna") |
///
/// # Example
///
/// ```rust
/// use krustie::{ Request, Response };
///
/// fn get(request: &Request, response: &mut Response) {
/// let id = request.get_query_param("id");
/// }
/// ```
pub fn get_query_param(&self, key: &str) -> Option<&String> {
self.queries.get(key)
}
/// Returns the path of the HTTP request as a Vector
///
/// | The path of the HTTP request | `get_path_array()` |
/// | -- | -- |
/// | `/` | `vec![]` |
/// | `/hello` | `vec!["hello"]` |
/// | `/hello/world` | `vec!["hello", "world"]` |
/// | `/hello/world?city=istanbul` | `vec!["hello", "world?city=istanbul"]` |
///
/// # Example
///
/// ```rust
/// use krustie::{ Request, Response };
///
/// fn get(request: &Request, response: &mut Response) {
/// let path: &Vec<String> = request.get_path_array();
/// }
/// ```
pub fn get_path_array(&self) -> &Vec<String> {
self.request.get_path_array()
}
/// Returns the path of the HTTP request as a String
///
/// # Example
///
/// ```rust
/// use krustie::{ Request, Response };
///
/// fn get(request: &Request, response: &mut Response) {
/// let path: &str = request.get_path();
/// }
/// ```
pub fn get_path(&self) -> &str {
self.request.get_path()
}
/// Returns the requested parameter of the HTTP request
///
/// | Route | Path | get_param(key: &str) | Returns |
/// | -- | -- | -- | -- |
/// | `/hello/:name` | `/hello/marvin` | `get_param("name")` | `Some("marvin")` |
/// | `/hello/:name` | `/hello/marvin` | `get_param("planet")` | `None` |
/// | `/hello/:name/:planet` | `/hello/marvin/earth` | `get_param("planet")` | `Some("earth")` |
///
/// # Example
///
/// ```rust
/// use krustie::{ Request, Response };
///
/// fn get(request: &Request, response: &mut Response) {
/// let sort: Option<&String> = request.get_param("sort");
/// }
/// ```
pub fn get_param(&self, key: &str) -> Option<&String> {
self.params.get(key)
}
/// Returns the version of the HTTP request
///
/// # Example
///
/// ```rust
/// use krustie::{HttpMethod, Request, Response};
///
/// # let request = Request::builder()
/// # .request_line(HttpMethod::GET, "/echo/hello", "HTTP/1.1")
/// # .build();
/// #
/// fn get(request: &Request, response: &mut Response) {
/// # }
/// assert_eq!(request.get_version(), "HTTP/1.1");
/// # {
/// }
/// ```
pub fn get_version(&self) -> &str {
&self.request.get_version()
}
/// Returns the method of the HTTP request
///
/// # Example
///
/// ```rust
/// use krustie::{HttpMethod, Request, Response};
///
/// # let request = Request::builder()
/// # .request_line(HttpMethod::GET, "/echo/hello", "HTTP/1.1")
/// # .build();
/// #
/// fn get(request: &Request, response: &mut Response) {
/// # }
/// assert_eq!(request.get_method(), &HttpMethod::GET);
/// # {
/// }
/// ```
pub fn get_method(&self) -> &HttpMethod {
self.request.get_method()
}
pub(crate) fn add_param(&mut self, params: HashMap<String, String>) {
self.params = params;
}
}
impl Default for Request {
fn default() -> Self {
Self {
request: RequestLine::new("GET", "/", "HTTP/1.1")
.expect("Failed to create default RequestLine"),
queries: HashMap::new(),
headers: HashMap::new(),
params: HashMap::new(),
body: RequestBody::None,
peer_addr: SocketAddr::new(IpAddr::V4(Ipv4Addr::new(0, 0, 0, 0)), 0),
}
}
}
impl Debug for Request {
fn fmt(&self, f: &mut Formatter<'_>) -> fResult {
fn format_hashmap(value: &HashMap<String, String>) -> String {
value
.iter()
.map(|(k, v)| format!(" {}: {}", k, v))
.collect::<Vec<String>>()
.join("\r\n")
}
let headers = format_hashmap(&self.headers);
let params = format_hashmap(&self.params);
let queries = format_hashmap(&self.queries);
let body = match &self.body {
RequestBody::Text(string) => format!("{:?}", string),
RequestBody::Json(json) => format!("{:?}", json),
RequestBody::Binary(body) => format!("{:?}", body),
RequestBody::None => "None".to_string(),
};
write!(
f,
"From:\r\n {}\r\nRequest Line:\r\n {}\r\nHeaders:\r\n{}\r\nParams:\r\n{}\r\nQueries:\r\n{}\r\nBody:\r\n{}",
self.peer_addr,
self.request,
headers,
params,
queries,
body
)
}
}
#[derive(Debug)]
/// Represents an error that occurs when parsing an HTTP request
pub struct ParseHttpRequestError;
impl Display for ParseHttpRequestError {
fn fmt(&self, f: &mut Formatter<'_>) -> fResult {
write!(f, "Failed to parse HTTP request")
}
}