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
use std::error::Error;
use std::fmt;
use iron::{Request, Response, Handler, IronResult, IronError};
use iron::status;
use iron::method::Method;
type PickerHandlers = Vec<(Option<Method>, Box<Handler>)>;
pub struct MethodPicker {
handlers: PickerHandlers
}
impl MethodPicker {
pub fn new() -> MethodPicker {
MethodPicker {
handlers: PickerHandlers::new()
}
}
pub fn add<H: Handler>(&mut self, method: Method, handler: H) -> &mut MethodPicker {
self.handlers.push((Some(method), Box::new(handler)));
self
}
pub fn get<H: Handler>(&mut self, handler: H) -> &mut MethodPicker {
self.handlers.push((Some(Method::Get), Box::new(handler)));
self
}
pub fn post<H: Handler>(&mut self, handler: H) -> &mut MethodPicker {
self.handlers.push((Some(Method::Post), Box::new(handler)));
self
}
pub fn put<H: Handler>(&mut self, handler: H) -> &mut MethodPicker {
self.handlers.push((Some(Method::Put), Box::new(handler)));
self
}
pub fn delete<H: Handler>(&mut self, handler: H) -> &mut MethodPicker {
self.handlers.push((Some(Method::Delete), Box::new(handler)));
self
}
pub fn head<H: Handler>(&mut self, handler: H) -> &mut MethodPicker {
self.handlers.push((Some(Method::Head), Box::new(handler)));
self
}
pub fn patch<H: Handler>(&mut self, handler: H) -> &mut MethodPicker {
self.handlers.push((Some(Method::Patch), Box::new(handler)));
self
}
pub fn options<H: Handler>(&mut self, handler: H) -> &mut MethodPicker {
self.handlers.push((Some(Method::Options), Box::new(handler)));
self
}
pub fn default<H: Handler>(&mut self, handler: H) -> &mut MethodPicker {
self.handlers.push((None, Box::new(handler)));
self
}
}
impl Handler for MethodPicker {
fn handle(&self, req: &mut Request) -> IronResult<Response> {
for &(ref method, ref handler) in self.handlers.iter() {
match method {
&Some(ref m) => if *m == req.method {
return handler.handle(req);
},
&None => return handler.handle(req)
}
}
Err(IronError::new(NoMethod, status::NotFound))
}
}
#[derive(Debug)]
pub struct NoMethod;
impl fmt::Display for NoMethod {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("No matching method found.")
}
}
impl Error for NoMethod {
fn description(&self) -> &str { "No method" }
}
#[macro_export]
macro_rules! picker {
($($method:ident => $handler:expr),+ $(,)*) => ({
let mut picker = $crate::MethodPicker::new();
$(picker.$method($handler);)*
picker
});
}