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
#![allow(deprecated)]
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use iron::{Request, Response, Handler, IronResult, IronError};
use iron::{status, method, headers};
use iron::typemap::Key;
use iron::modifiers::Redirect;
use recognizer::Router as Recognizer;
use recognizer::{Match, Params};
pub struct Router {
routers: HashMap<method::Method, Recognizer<Box<Handler>>>
}
impl Router {
pub fn new() -> Router {
Router {
routers: HashMap::new()
}
}
pub fn route<H, S>(&mut self, method: method::Method,
glob: S, handler: H) -> &mut Router
where H: Handler, S: AsRef<str> {
self.routers.entry(method).or_insert(Recognizer::new())
.add(glob.as_ref(), Box::new(handler));
self
}
pub fn get<H: Handler, S: AsRef<str>>(&mut self, glob: S, handler: H) -> &mut Router {
self.route(method::Get, glob, handler)
}
pub fn post<H: Handler, S: AsRef<str>>(&mut self, glob: S, handler: H) -> &mut Router {
self.route(method::Post, glob, handler)
}
pub fn put<H: Handler, S: AsRef<str>>(&mut self, glob: S, handler: H) -> &mut Router {
self.route(method::Put, glob, handler)
}
pub fn delete<H: Handler, S: AsRef<str>>(&mut self, glob: S, handler: H) -> &mut Router {
self.route(method::Delete, glob, handler)
}
pub fn head<H: Handler, S: AsRef<str>>(&mut self, glob: S, handler: H) -> &mut Router {
self.route(method::Head, glob, handler)
}
pub fn patch<H: Handler, S: AsRef<str>>(&mut self, glob: S, handler: H) -> &mut Router {
self.route(method::Patch, glob, handler)
}
pub fn options<H: Handler, S: AsRef<str>>(&mut self, glob: S, handler: H) -> &mut Router {
self.route(method::Options, glob, handler)
}
fn recognize(&self, method: &method::Method, path: &str)
-> Option<Match<&Box<Handler>>> {
self.routers.get(method).and_then(|router| router.recognize(path).ok())
}
fn handle_options(&self, path: &str) -> Response {
static METHODS: &'static [method::Method] =
&[method::Get, method::Post, method::Post, method::Put,
method::Delete, method::Head, method::Patch];
let mut options = vec![];
for method in METHODS.iter() {
self.routers.get(method).map(|router| {
if let Some(_) = router.recognize(path).ok() {
options.push(method.clone());
}
});
}
if options.contains(&method::Get) && !options.contains(&method::Head) {
options.push(method::Head);
}
let mut res = Response::with(status::Ok);
res.headers.set(headers::Allow(options));
res
}
fn redirect_slash(&self, req : &Request) -> Option<IronError> {
let mut url = req.url.clone();
let mut path = url.path.connect("/");
if let Some(last_char) = path.chars().last() {
if last_char == '/' {
path.pop();
url.path.pop();
} else {
path.push('/');
url.path.push("".to_string());
}
}
self.recognize(&req.method, &path).and(
Some(IronError::new(TrailingSlash,
(status::MovedPermanently, Redirect(url))))
)
}
fn handle_method(&self, req: &mut Request, path: &str) -> Option<IronResult<Response>> {
if let Some(matched) = self.recognize(&req.method, path) {
req.extensions.insert::<Router>(matched.params);
Some(matched.handler.handle(req))
} else { self.redirect_slash(req).and_then(|redirect| Some(Err(redirect))) }
}
}
impl Key for Router { type Value = Params; }
impl Handler for Router {
fn handle(&self, req: &mut Request) -> IronResult<Response> {
let path = req.url.path.connect("/");
self.handle_method(req, &path).unwrap_or_else(||
match req.method {
method::Options => Ok(self.handle_options(&path)),
method::Head => {
req.method = method::Get;
self.handle_method(req, &path).unwrap_or(
Err(IronError::new(NoRoute, status::NotFound))
)
}
_ => Err(IronError::new(NoRoute, status::NotFound))
}
)
}
}
#[derive(Debug)]
pub struct NoRoute;
impl fmt::Display for NoRoute {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("No matching route found.")
}
}
impl Error for NoRoute {
fn description(&self) -> &str { "No Route" }
}
#[derive(Debug)]
pub struct TrailingSlash;
impl fmt::Display for TrailingSlash {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("The request had a trailing slash.")
}
}
impl Error for TrailingSlash {
fn description(&self) -> &str { "Trailing Slash" }
}