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
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
use futures::{future, IntoFuture};
use hyper;
use hyper::error::Error;
use hyper::rt::Future;
use hyper::service::Service;
use hyper::{Body, Method, Request, Response, StatusCode};
use path::clean_path;
use std::collections::BTreeMap;
use std::ops::Index;
use tokio_fs;
use tokio_io;
use tree::Node;
use std::path::Path;
pub type BoxFut = Box<Future<Item = Response<Body>, Error = hyper::Error> + Send>;
pub trait Handle {
fn handle(&self, req: Request<Body>, ps: Params) -> BoxFut;
}
impl<F> Handle for F
where
F: Fn(Request<Body>, Params) -> BoxFut,
{
fn handle(&self, req: Request<Body>, ps: Params) -> BoxFut {
(*self)(req, ps)
}
}
pub type Handler = Box<Handle + Send>;
#[derive(Debug, Clone, PartialEq)]
pub struct Param {
pub key: String,
pub value: String,
}
impl Param {
pub fn new(key: &str, value: &str) -> Param {
Param {
key: key.to_string(),
value: value.to_string(),
}
}
}
#[derive(Debug, PartialEq)]
pub struct Params(pub Vec<Param>);
impl Params {
pub fn by_name(&self, name: &str) -> Option<&str> {
match self.0.iter().find(|param| param.key == name) {
Some(param) => Some(¶m.value),
None => None,
}
}
pub fn new() -> Params {
Params(Vec::new())
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn push(&mut self, p: Param) {
self.0.push(p);
}
}
impl Index<usize> for Params {
type Output = str;
fn index(&self, i: usize) -> &Self::Output {
&(self.0)[i].value
}
}
#[allow(dead_code)]
pub struct Router<T> {
pub trees: BTreeMap<String, Node<T>>,
pub redirect_trailing_slash: bool,
pub redirect_fixed_path: bool,
pub handle_method_not_allowed: bool,
pub handle_options: bool,
pub not_found: Option<T>,
pub method_not_allowed: Option<T>,
pub panic_handler: Option<T>,
}
impl<T> Router<T> {
pub fn new() -> Router<T> {
Router {
trees: BTreeMap::new(),
redirect_trailing_slash: true,
redirect_fixed_path: true,
handle_method_not_allowed: true,
handle_options: true,
not_found: None,
method_not_allowed: None,
panic_handler: None,
}
}
pub fn get(&mut self, path: &str, handle: T) {
self.handle("GET", path, handle);
}
pub fn head(&mut self, path: &str, handle: T) {
self.handle("HEAD", path, handle);
}
pub fn options(&mut self, path: &str, handle: T) {
self.handle("OPTIONS", path, handle);
}
pub fn post(&mut self, path: &str, handle: T) {
self.handle("POST", path, handle);
}
pub fn put(&mut self, path: &str, handle: T) {
self.handle("PUT", path, handle);
}
pub fn patch(&mut self, path: &str, handle: T) {
self.handle("PATCH", path, handle);
}
pub fn delete(&mut self, path: &str, handle: T) {
self.handle("DELETE", path, handle);
}
pub fn group() {
unimplemented!()
}
pub fn handle(&mut self, method: &str, path: &str, handle: T) {
if !path.starts_with("/") {
panic!("path must begin with '/' in path '{}'", path);
}
self.trees
.entry(method.to_string())
.or_insert(Node::new())
.add_route(path, handle);
}
pub fn lookup(&mut self, method: &str, path: &str) -> (Option<&T>, Params, bool) {
self.trees
.get_mut(method)
.and_then(|n| Some(n.get_value(path)))
.unwrap_or((None, Params::new(), false))
}
pub fn allowed(&self, path: &str, req_method: &str) -> String {
let mut allow = String::new();
if path == "*" {
for method in self.trees.keys() {
if method == "OPTIONS" {
continue;
}
if allow.is_empty() {
allow.push_str(method);
} else {
allow.push_str(", ");
allow.push_str(method);
}
}
} else {
for method in self.trees.keys() {
if method == req_method || method == "OPTIONS" {
continue;
}
self.trees.get(method).map(|tree| {
let (handle, _, _) = tree.get_value(path);
if handle.is_some() {
if allow.is_empty() {
allow.push_str(method);
} else {
allow.push_str(", ");
allow.push_str(method);
}
}
});
}
}
if allow.len() > 0 {
allow += ", OPTIONS";
}
allow
}
}
impl Service for Router<Handler> {
type ReqBody = Body;
type ResBody = Body;
type Error = Error;
type Future = BoxFut;
fn call(&mut self, req: Request<Self::ReqBody>) -> Self::Future {
let root = self.trees.get(req.method().as_str());
if let Some(root) = root {
let (handle, ps, tsr) = root.get_value(req.uri().path());
if let Some(handle) = handle {
return handle.handle(req, ps);
} else if req.method() != &Method::CONNECT && req.uri().path() != "/" {
let code = if req.method() != &Method::GET {
307
} else {
301
};
if tsr && self.redirect_trailing_slash {
let path = if req.uri().path().len() > 1 && req.uri().path().ends_with("/") {
req.uri().path()[..req.uri().path().len() - 1].to_string()
} else {
req.uri().path().to_string() + "/"
};
let response = Response::builder()
.header("Location", path.as_str())
.status(code)
.body(Body::empty())
.unwrap();
return Box::new(future::ok(response));
}
if self.redirect_fixed_path {
let (fixed_path, found) = root.find_case_insensitive_path(
&clean_path(req.uri().path()),
self.redirect_trailing_slash,
);
if found {
let response = Response::builder()
.header("Location", fixed_path.as_str())
.status(code)
.body(Body::empty())
.unwrap();
return Box::new(future::ok(response));
}
}
}
}
if req.method() == &Method::OPTIONS && self.handle_options {
let allow = self.allowed(req.uri().path(), req.method().as_str());
if allow.len() > 0 {
let response = Response::builder()
.header("Allow", allow.as_str())
.body(Body::empty())
.unwrap();
return Box::new(future::ok(response));
}
} else {
if self.handle_method_not_allowed {
let allow = self.allowed(req.uri().path(), req.method().as_str());
if allow.len() > 0 {
let mut response = Response::builder()
.header("Allow", allow.as_str())
.body(Body::empty())
.unwrap();
if let Some(ref method_not_allowed) = self.method_not_allowed {
return method_not_allowed.handle(req, Params::new());
} else {
*response.status_mut() = StatusCode::METHOD_NOT_ALLOWED;
*response.body_mut() = Body::from("METHOD_NOT_ALLOWED");
}
return Box::new(future::ok(response));
}
}
}
if let Some(ref not_found) = self.not_found {
return not_found.handle(req, Params::new());
} else {
let response = Response::builder()
.status(404)
.body("NOT_FOUND".into())
.unwrap();
return Box::new(future::ok(response));
}
}
}
impl IntoFuture for Router<Handler> {
type Future = future::FutureResult<Self::Item, Self::Error>;
type Item = Self;
type Error = Error;
fn into_future(self) -> Self::Future {
future::ok(self)
}
}
impl Router<Handler> {
pub fn serve_files(&mut self, path: &str, root: &'static str) {
if path.as_bytes().len() < 10 || &path[path.len() - 10..] != "/*filepath" {
panic!("path must end with /*filepath in path '{}'", path);
}
let root_path = Path::new(root);
let get_files = move |_, ps: Params| -> BoxFut {
let filepath = ps.by_name("filepath").unwrap();
simple_file_send(root_path.join(&filepath[1..]).to_str().unwrap())
};
self.get(path, Box::new(get_files));
}
}
fn simple_file_send(f: &str) -> BoxFut {
let filename = f.to_string();
Box::new(
tokio_fs::file::File::open(filename)
.and_then(|file| {
let buf: Vec<u8> = Vec::new();
tokio_io::io::read_to_end(file, buf)
.and_then(|item| Ok(Response::new(item.1.into())))
.or_else(|_| {
Ok(Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(Body::empty())
.unwrap())
})
})
.or_else(|_| {
Ok(Response::builder()
.status(StatusCode::NOT_FOUND)
.body(Body::from("NOT_FOUND"))
.unwrap())
}),
)
}
#[cfg(test)]
mod tests {
#[test]
fn params() {
use router::{Param, Params};
let params = Params(vec![
Param {
key: "hello".to_owned(),
value: "world".to_owned(),
},
Param {
key: "lalala".to_string(),
value: "papapa".to_string(),
},
]);
assert_eq!(Some("world"), params.by_name("hello"));
assert_eq!(Some("papapa"), params.by_name("lalala"));
}
#[test]
#[should_panic(expected = "path must begin with '/' in path 'something'")]
fn handle_ivalid_path() {
use futures::future;
use hyper::{Body, Request, Response};
use router::{BoxFut, Params, Router};
let path = "something";
let mut router = Router::new();
router.handle("GET", path, |_req: Request<Body>, _: Params| -> BoxFut {
Box::new(future::ok(Response::new(Body::from("test"))))
});
}
}