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
extern crate hyper;
extern crate regex;
use std::collections::HashMap;
use hyper::method::Method;
use hyper::server::{Handler, Request, Response};
use hyper::status::StatusCode;
use regex::{Regex, RegexSet};
use error::RouterError;
pub type Captures = Option<Vec<String>>;
pub type NotFoundFn = fn(Request, Response);
#[derive(PartialEq, Eq, Hash)]
pub struct RouteInfo {
route: String,
verb: Method
}
pub struct Router {
pub not_found: Option<NotFoundFn>,
routes: Option<RegexSet>,
route_list: Vec<String>,
compiled_list: Vec<Regex>,
route_map: HashMap<RouteInfo, Box<Fn(Request, Response, Captures)>>
}
unsafe impl Send for Router { }
unsafe impl Sync for Router { }
impl Handler for Router {
fn handle(&self, req: Request, res: Response) {
let uri = format!("{}", req.uri);
let matches = self.routes.as_ref().unwrap().matches(&uri);
let index = matches.iter().next();
match index {
Some(i) => {
let route = &self.route_list[i];
let route_info = RouteInfo{route: route.clone(), verb: req.method.clone()};
let handler = self.route_map.get(&route_info);
match handler {
Some(h) => {
let compiled_pattern = &self.compiled_list[i];
let captures = get_captures(compiled_pattern, &uri);
h(req, res, captures);
}
None => {
not_allowed(req, res);
}
}
},
None => self.not_found.unwrap()(req, res)
}
}
}
impl Router {
pub fn new() -> Router {
Router {
not_found: None,
routes: None,
route_list: Vec::new(),
compiled_list: Vec::new(),
route_map: HashMap::new(),
}
}
pub fn add_route<H>(&mut self, verb: Method, route: &str, handler: H)
where H: Fn(Request, Response, Captures) + Send + Sync + 'static {
let route_info = RouteInfo{route: route.to_owned(), verb: verb};
let pattern = Regex::new(route);
match pattern {
Ok(p) => { self.compiled_list.push(p); },
Err(e) => { println!("Not adding this route due to error: {}", e); }
}
self.route_list.push(route.to_owned());
self.route_map.insert(route_info, Box::new(handler));
}
pub fn options<H>(&mut self, route: &str, handler: H)
where H: Fn(Request, Response, Captures) + Send + Sync + 'static {
self.add_route(Method::Options, route, handler);
}
pub fn get<H>(&mut self, route: &str, handler: H)
where H: Fn(Request, Response, Captures) + Send + Sync + 'static {
self.add_route(Method::Get, route, handler);
}
pub fn post<H>(&mut self, route: &str, handler: H)
where H: Fn(Request, Response, Captures) + Send + Sync + 'static {
self.add_route(Method::Post, route, handler);
}
pub fn put<H>(&mut self, route: &str, handler: H)
where H: Fn(Request, Response, Captures) + Send + Sync + 'static {
self.add_route(Method::Put, route, handler);
}
pub fn delete<H>(&mut self, route: &str, handler: H)
where H: Fn(Request, Response, Captures) + Send + Sync + 'static {
self.add_route(Method::Delete, route, handler);
}
pub fn finalize(&mut self) -> Result<(), RouterError> {
if self.route_list.len() == 0 {
return Err(RouterError::TooFewRoutes);
}
match self.not_found {
Some(_) => {},
None => { self.not_found = Some(default_not_found); }
}
let re_routes = RegexSet::new(self.route_list.iter());
match re_routes {
Ok(r) => {
self.routes = Some(r);
Ok(())
}
Err(_) => {
Err(RouterError::BadSet)
}
}
}
pub fn add_not_found(&mut self, not_found: NotFoundFn) {
self.not_found = Some(not_found)
}
}
fn default_not_found(req: Request, mut res: Response) {
let message = format!("No route handler found for {}", req.uri);
*res.status_mut() = StatusCode::NotFound;
res.send(message.as_bytes()).unwrap();
}
fn not_allowed(_: Request, mut res: Response) {
*res.status_mut() = StatusCode::MethodNotAllowed;
let res = res.start().unwrap();
res.end().unwrap();
}
fn get_captures(pattern: &Regex, uri: &str) -> Captures {
let caps = pattern.captures(uri);
match caps {
Some(caps) => {
let mut v = vec![];
for c in caps.iter() {
v.push(c.unwrap().to_owned());
}
Some(v)
},
None => None
}
}
mod error;
#[test]
fn no_routes() {
let mut router = Router::new();
let e = router.finalize();
assert_eq!(e.err(), Some(RouterError::TooFewRoutes));
}
#[test]
fn bad_regular_expression() {
fn test_handler(_: Request, _: Response, _: Captures) {}
let mut router = Router::new();
router.add_route(Method::Get, r"/[", test_handler);
let e = router.finalize();
assert_eq!(e.err(), Some(RouterError::BadSet));
}