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
use std::collections::HashMap;
use std::error::Error;
use std::fmt;
use std::sync::Arc;
use iron::{Request, Response, BeforeMiddleware, Handler, IronResult, IronError};
use iron::{status, method, headers};
use iron::typemap::Key;
use iron::modifiers::Redirect;
use route_recognizer::Router as Recognizer;
use route_recognizer::{Match, Params};
#[derive(Clone)]
pub struct MetaRouter {
routers: HashMap<method::Method, Recognizer<Box<String>>>,
wildcard: Recognizer<Box<String>>,
}
pub struct RouterInner {
pub routers: HashMap<method::Method, Recognizer<Box<Handler>>>,
pub wildcard: Recognizer<Box<Handler>>,
pub route_ids: HashMap<String, String>,
pub meta_router: MetaRouter,
}
pub struct Router {
inner: Arc<RouterInner>
}
pub struct RouteMatch {
pub params: Params,
pub route_id: String
}
impl MetaRouter {
fn recognize(&self, method: &method::Method, path: &str)
-> Option<Match<&Box<String>>> {
self.routers.get(method).and_then(|router| router.recognize(path).ok())
.or(self.wildcard.recognize(path).ok())
}
pub fn analyse_method(&self, req: &mut Request, path: &str) -> Option<RouteMatch> {
if let Some(matched) = self.recognize(&req.method, path) {
let ctx = RouteMatch {
params: matched.params,
route_id: matched.route_id
};
Some(ctx)
} else {
None
}
}
}
impl Router {
pub fn new() -> Router {
Router {
inner: Arc::new(RouterInner {
routers: HashMap::new(),
wildcard: Recognizer::new(),
route_ids: HashMap::new(),
meta_router: MetaRouter {
routers: HashMap::new(),
wildcard: Recognizer::new()
}
})
}
}
fn mut_inner(&mut self) -> &mut RouterInner {
Arc::get_mut(&mut self.inner).expect("Cannot modify router at this point.")
}
pub fn route<S: AsRef<str>, H: Handler>(&mut self, method: method::Method, glob: S, handler: H, route_id: &str) -> &mut Router {
self.mut_inner().routers
.entry(method.clone())
.or_insert(Recognizer::new())
.add(glob.as_ref(), route_id, Box::new(handler));
self.route_id(route_id.as_ref(), glob.as_ref());
self.mut_inner().meta_router.routers
.entry(method)
.or_insert(Recognizer::new())
.add(glob.as_ref(), route_id, Box::new("".to_string()));
self
}
fn route_id(&mut self, id: &str, glob: &str) {
let inner = self.mut_inner();
let ref mut route_ids = inner.route_ids;
match route_ids.get(id) {
Some(other_glob) if glob != other_glob => panic!("Duplicate route_id: {}", id),
_ => ()
};
route_ids.insert(id.to_owned(), glob.to_owned());
}
pub fn get<S: AsRef<str>, H: Handler>(&mut self, glob: S, handler: H, route_id: &str) -> &mut Router {
self.route(method::Get, glob, handler, route_id)
}
pub fn post<S: AsRef<str>, H: Handler>(&mut self, glob: S, handler: H, route_id: &str) -> &mut Router {
self.route(method::Post, glob, handler, route_id)
}
pub fn put<S: AsRef<str>, H: Handler>(&mut self, glob: S, handler: H, route_id: &str) -> &mut Router {
self.route(method::Put, glob, handler, route_id)
}
pub fn delete<S: AsRef<str>, H: Handler>(&mut self, glob: S, handler: H, route_id: &str) -> &mut Router {
self.route(method::Delete, glob, handler, route_id)
}
pub fn head<S: AsRef<str>, H: Handler>(&mut self, glob: S, handler: H, route_id: &str) -> &mut Router {
self.route(method::Head, glob, handler, route_id)
}
pub fn patch<S: AsRef<str>, H: Handler>(&mut self, glob: S, handler: H, route_id: &str) -> &mut Router {
self.route(method::Patch, glob, handler, route_id)
}
pub fn options<S: AsRef<str>, H: Handler>(&mut self, glob: S, handler: H, route_id: &str) -> &mut Router {
self.route(method::Options, glob, handler, route_id)
}
pub fn any<S: AsRef<str>, H: Handler>(&mut self, glob: S, handler: H, route_id: &str) -> &mut Router {
self.mut_inner().wildcard.add(glob.as_ref(), route_id, Box::new(handler));
self.route_id(route_id.as_ref(), glob.as_ref());
self
}
fn recognize(&self, method: &method::Method, path: &str)
-> Option<Match<&Box<Handler>>> {
self.inner.routers.get(method).and_then(|router| router.recognize(path).ok())
.or(self.inner.wildcard.recognize(path).ok())
}
fn handle_options(&self, path: &str) -> Response {
static METHODS: &'static [method::Method] =
&[method::Get, method::Post, method::Put,
method::Delete, method::Head, method::Patch];
let mut options = vec![];
for method in METHODS.iter() {
self.inner.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().join("/");
if let Some(last_char) = path.chars().last() {
{
let mut path_segments = url.as_mut().path_segments_mut().unwrap();
if last_char == '/' {
path.pop();
path_segments.pop();
} else {
path.push('/');
path_segments.push("");
}
}
}
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) {
let ctx = RouteMatch {
params: matched.params,
route_id: matched.route_id
};
req.extensions.insert::<Router>(ctx);
req.extensions.insert::<RouterInner>(self.inner.clone());
Some(matched.handler.handle(req))
} else { self.redirect_slash(req).and_then(|redirect| Some(Err(redirect))) }
}
pub fn to_meta(&self) -> MetaRouter {
self.inner.meta_router.clone()
}
}
impl Key for Router { type Value = RouteMatch; }
impl Key for RouterInner { type Value = Arc<RouterInner>; }
impl Key for MetaRouter { type Value = RouteMatch; }
impl Handler for Router {
fn handle(&self, req: &mut Request) -> IronResult<Response> {
let path = req.url.path().join("/");
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))
}
)
}
}
impl BeforeMiddleware for MetaRouter {
fn before(&self, req: &mut Request) -> IronResult<()> {
let path = req.url.path().join("/");
match self.analyse_method(req, &path) {
None => Ok(()),
Some(ctx) => {
req.extensions.insert::<MetaRouter>(ctx);
Ok(())
}
}
}
}
#[derive(Debug, PartialEq, Eq)]
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, PartialEq, Eq)]
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" }
}
#[cfg(test)]
mod test {
use super::Router;
use iron::{headers, method, status, Request, Response};
#[test]
fn test_route_id_correct() {
let mut router = Router::new();
router.post("/api/xyz", |_: &mut Request| {
Ok(Response::with((status::Ok, "")))
}, "a");
let mut router = Router::new();
router.post("/api/v2/xyz", |_: &mut Request| {
Ok(Response::with((status::Ok, "")))
}, "b");
let res = router.recognize(&method::Method::Post, "api/v2/xyz");
assert!(res.is_some());
let res = res.unwrap();
assert_eq!(res.route_id, "b");
}
#[test]
fn test_meta_route_id_correct() {
let mut router = Router::new();
router.get("/api/xyz", |_: &mut Request| {
Ok(Response::with((status::Ok, "")))
}, "a");
let mut router = Router::new();
router.get("/api/v2/xyz", |_: &mut Request| {
Ok(Response::with((status::Ok, "")))
}, "b");
let meta = router.to_meta();
let res = meta.recognize(&method::Method::Get, "api/v2/xyz");
assert!(res.is_some());
let res = res.unwrap();
assert_eq!(res.route_id, "b");
}
#[test]
fn test_handle_options_post() {
let mut router = Router::new();
router.post("/", |_: &mut Request| {
Ok(Response::with((status::Ok, "")))
}, "");
let resp = router.handle_options("/");
let headers = resp.headers.get::<headers::Allow>().unwrap();
let expected = headers::Allow(vec![method::Method::Post]);
assert_eq!(&expected, headers);
}
#[test]
fn test_handle_options_get_head() {
let mut router = Router::new();
router.get("/", |_: &mut Request| {
Ok(Response::with((status::Ok, "")))
}, "");
let resp = router.handle_options("/");
let headers = resp.headers.get::<headers::Allow>().unwrap();
let expected = headers::Allow(vec![method::Method::Get, method::Method::Head]);
assert_eq!(&expected, headers);
}
#[test]
fn test_handle_any_ok() {
let mut router = Router::new();
router.post("/post", |_: &mut Request| {
Ok(Response::with((status::Ok, "")))
}, "");
router.any("/post", |_: &mut Request| {
Ok(Response::with((status::Ok, "")))
}, "");
router.put("/post", |_: &mut Request| {
Ok(Response::with((status::Ok, "")))
}, "");
router.any("/get", |_: &mut Request| {
Ok(Response::with((status::Ok, "")))
}, "any");
assert!(router.recognize(&method::Get, "/post").is_some());
assert!(router.recognize(&method::Get, "/get").is_some());
}
#[test]
fn test_request() {
let mut router = Router::new();
router.post("/post", |_: &mut Request| {
Ok(Response::with((status::Ok, "")))
}, "");
router.get("/post", |_: &mut Request| {
Ok(Response::with((status::Ok, "")))
}, "");
assert!(router.recognize(&method::Post, "/post").is_some());
assert!(router.recognize(&method::Get, "/post").is_some());
assert!(router.recognize(&method::Put, "/post").is_none());
assert!(router.recognize(&method::Get, "/post/").is_none());
}
#[test]
fn test_not_found() {
let mut router = Router::new();
router.put("/put", |_: &mut Request| {
Ok(Response::with((status::Ok, "")))
}, "");
assert!(router.recognize(&method::Patch, "/patch").is_none());
}
#[test]
#[should_panic]
fn test_same_route_id() {
let mut router = Router::new();
router.put("/put", |_: &mut Request| {
Ok(Response::with((status::Ok, "")))
}, "my_route_id");
router.get("/get", |_: &mut Request| {
Ok(Response::with((status::Ok, "")))
}, "my_route_id");
}
#[test]
fn test_wildcard_regression() {
let mut router = Router::new();
router.options("*", |_: &mut Request| Ok(Response::with((status::Ok, ""))), "id1");
router.put("/upload/*filename", |_: &mut Request| Ok(Response::with((status::Ok, ""))), "id2");
assert!(router.recognize(&method::Options, "/foo").is_some());
assert!(router.recognize(&method::Put, "/foo").is_none());
assert!(router.recognize(&method::Put, "/upload/foo").is_some());
}
}