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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
#![allow(unused_imports)]
#![allow(unused_variables)]
use std::cmp::Ordering;
use std::collections::{HashMap, HashSet};
use std::io::Error;
use std::sync::mpsc;
use std::time::Duration;
use super::http::{Request, RequestWriter, Response, ResponseStates, ResponseWriter};
use regex::Regex;
use support::common::MapUpdates;
use support::debug;
use support::TaskType;
use support::{shared_pool, RouteTrie};
lazy_static! {
static ref ROUTE_ALL: REST = REST::OTHER(String::from("*"));
}
#[derive(PartialEq, Eq, Hash, Clone)]
pub enum REST {
GET,
PATCH,
POST,
PUT,
DELETE,
OPTIONS,
OTHER(String),
}
#[derive(PartialEq, Eq, Hash, Clone, Copy)]
pub enum RequestPath {
Explicit(&'static str),
ExplicitWithParams(&'static str),
WildCard(&'static str),
}
pub type Callback = fn(&Box<Request>, &mut Box<Response>);
pub type AuthFunc = fn(&Box<Request>, String) -> bool;
struct RegexRoute {
pub regex: Regex,
pub handler: Callback,
}
impl RegexRoute {
pub fn new(re: Regex, handler: Callback) -> Self {
RegexRoute { regex: re, handler }
}
}
impl Clone for RegexRoute {
fn clone(&self) -> Self {
RegexRoute {
regex: self.regex.clone(),
handler: self.handler,
}
}
}
pub struct RouteMap {
explicit: HashMap<String, Callback>,
explicit_with_params: RouteTrie,
wildcard: HashMap<String, RegexRoute>,
}
impl RouteMap {
pub fn new() -> Self {
RouteMap {
explicit: HashMap::new(),
explicit_with_params: RouteTrie::initialize(),
wildcard: HashMap::new(),
}
}
pub fn insert(&mut self, uri: RequestPath, callback: Callback) {
match uri {
RequestPath::Explicit(req_uri) => {
if req_uri.is_empty() || !req_uri.starts_with('/') {
panic!("Request path must have valid contents and start with '/'.");
}
self.explicit.add(req_uri, callback, false);
},
RequestPath::WildCard(req_uri) => {
if req_uri.is_empty() {
panic!("Request path must have valid contents.");
}
if self.wildcard.contains_key(req_uri) {
return;
}
if let Ok(re) = Regex::new(req_uri) {
self.wildcard
.add(req_uri, RegexRoute::new(re, callback), false);
}
},
RequestPath::ExplicitWithParams(req_uri) => {
if !req_uri.contains("/:") && !req_uri.contains(":\\") {
self.explicit.add(req_uri, callback, false);
return;
}
let segments: Vec<String> = req_uri
.trim_matches('/')
.split('/')
.filter(|s| !s.is_empty())
.map(|s| s.to_owned())
.collect();
if let Err(e) = validate_segments(&segments) {
panic!("{}", e);
}
self.explicit_with_params.add(segments, callback);
},
}
}
fn seek_path(&self, uri: &str, params: &mut HashMap<String, String>) -> Option<Callback> {
if let Some(callback) = self.explicit.get(uri) {
return Some(*callback);
}
if !self.explicit_with_params.is_empty() {
let (callback, temp_params) =
search_params_router(&self.explicit_with_params, uri);
if callback.is_some() {
for param in temp_params {
params.insert(param.0, param.1);
}
return callback;
}
}
if !self.wildcard.is_empty() {
return search_wildcard_router(&self.wildcard, uri);
}
None
}
}
impl Clone for RouteMap {
fn clone(&self) -> Self {
RouteMap {
explicit: self.explicit.clone(),
explicit_with_params: self.explicit_with_params.clone(),
wildcard: self.wildcard.clone(),
}
}
}
pub struct Route {
store: Box<HashMap<REST, RouteMap>>,
auth_func: Option<AuthFunc>,
}
impl Route {
pub fn new() -> Self {
Route {
store: Box::from(HashMap::new()),
auth_func: None,
}
}
#[inline]
pub fn get_auth_func(&self) -> Option<AuthFunc> {
self.auth_func.clone()
}
#[inline]
pub fn set_auth_func(&mut self, auth_func: Option<AuthFunc>) {
self.auth_func = auth_func;
}
fn add_route(&mut self, method: REST, uri: RequestPath, callback: Callback) {
if let Some(route) = self.store.get_mut(&method) {
route.insert(uri, callback);
return;
}
let mut route = RouteMap::new();
route.insert(uri, callback);
self.store.insert(method, route);
}
}
impl Clone for Route {
fn clone(&self) -> Self {
Route {
store: self.store.clone(),
auth_func: self.auth_func.clone(),
}
}
}
pub trait Router {
fn get(&mut self, uri: RequestPath, callback: Callback) -> &mut Route;
fn patch(&mut self, uri: RequestPath, callback: Callback) -> &mut Route;
fn post(&mut self, uri: RequestPath, callback: Callback) -> &mut Route;
fn put(&mut self, uri: RequestPath, callback: Callback) -> &mut Route;
fn delete(&mut self, uri: RequestPath, callback: Callback) -> &mut Route;
fn options(&mut self, uri: RequestPath, callback: Callback) -> &mut Route;
fn other(&mut self, method: &str, uri: RequestPath, callback: Callback) -> &mut Route;
fn all(&mut self, uri: RequestPath, callback: Callback) -> &mut Route;
}
impl Router for Route {
fn get(&mut self, uri: RequestPath, callback: Callback) -> &mut Route {
self.add_route(REST::GET, uri, callback);
self
}
fn patch(&mut self, uri: RequestPath, callback: Callback) -> &mut Route {
self.add_route(REST::PATCH, uri, callback);
self
}
fn post(&mut self, uri: RequestPath, callback: Callback) -> &mut Route {
self.add_route(REST::POST, uri, callback);
self
}
fn put(&mut self, uri: RequestPath, callback: Callback) -> &mut Route {
self.add_route(REST::PUT, uri, callback);
self
}
fn delete(&mut self, uri: RequestPath, callback: Callback) -> &mut Route {
self.add_route(REST::DELETE, uri, callback);
self
}
fn options(&mut self, uri: RequestPath, callback: Callback) -> &mut Route {
self.add_route(REST::OPTIONS, uri, callback);
self
}
fn other(&mut self, method: &str, uri: RequestPath, callback: Callback) -> &mut Route {
if method.is_empty() {
panic!("Must provide a valid method!");
}
let request_method = REST::OTHER(method.to_uppercase());
self.add_route(request_method, uri, callback);
self
}
fn all(&mut self, uri: RequestPath, callback: Callback) -> &mut Route {
self.other("*", uri.clone(), callback)
}
}
pub trait RouteHandler {
fn handle_request(callback: Callback, req: &Box<Request>, resp: &mut Box<Response>);
fn seek_handler(
&self,
method: &REST,
uri: &str,
header_only: bool,
tx: mpsc::Sender<(Option<Callback>, HashMap<String, String>)>,
);
}
impl RouteHandler for Route {
fn handle_request(callback: Callback, req: &Box<Request>, resp: &mut Box<Response>) {
callback(req, resp);
let mut redirect = resp.get_redirect_path();
if !redirect.is_empty() {
if !redirect.starts_with('/') {
redirect.insert(0, '/');
}
resp.header("Location", &redirect, true);
resp.status(301);
}
}
fn seek_handler(
&self,
method: &REST,
uri: &str,
header_only: bool,
tx: mpsc::Sender<(Option<Callback>, HashMap<String, String>)>,
) {
let mut result = None;
let mut params = HashMap::new();
if let Some(routes) = self.store.get(method) {
result = routes.seek_path(uri, &mut params);
} else if header_only {
if let Some(routes) = self.store.get(&REST::GET) {
result = routes.seek_path(uri, &mut params);
}
}
if result.is_none() {
if let Some(all_routes) = self.store.get(&ROUTE_ALL) {
result = all_routes.seek_path(uri, &mut params);
}
}
if let Err(e) = tx.send((result, params)) {
debug::print("Unable to find the route handler", 2);
}
}
}
fn search_wildcard_router(routes: &HashMap<String, RegexRoute>, uri: &str) -> Option<Callback> {
let mut result = None;
for (_, route) in routes.iter() {
if route.regex.is_match(&uri) {
result = Some(route.handler);
break;
}
}
result
}
fn search_params_router(
route_head: &RouteTrie,
uri: &str,
) -> (Option<Callback>, Vec<(String, String)>) {
let raw_segments: Vec<String> =
uri.trim_matches('/')
.split('/')
.map(|s| s.to_owned())
.collect();
let mut params: Vec<(String, String)> = Vec::new();
let result =
RouteTrie::find(&route_head.root, raw_segments.as_slice(), &mut params);
(result, params)
}
fn validate_segments(segments: &Vec<String>) -> Result<(), String> {
let mut param_names = HashSet::new();
for seg in segments {
if seg.starts_with(':') {
if seg.len() == 1 {
return Err(String::from("Route parameter name can't be null"));
} else if param_names.contains(seg) {
return Err(format!("Route parameters must have unique name: {}", seg));
} else {
param_names.insert(seg);
}
}
}
Ok(())
}