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
use std::collections::HashMap;
use std::collections::HashSet;
use regex::Regex;
use regex::escape as regex_quote;
use hyper::method::Method;
use http_errors::{HTTPError, MethodNotAllowed, NotFound};
use types::ViewArgs;
use utils::join_string;
fn parse_rule(rule: &str) -> Vec<(Option<&str>, &str)> {
let rule_re = Regex::new(r"(?x)
(?P<static>[^<]*) # static rule data
<
(?:
(?P<variable>[a-zA-Z_][a-zA-Z0-9_]*) # variable name
: # variable delimiter
)?
(?P<converter>[a-zA-Z_][a-zA-Z0-9_]*) # converter name
>
").unwrap();
let mut rule_parts: Vec<(Option<&str>, &str)> = Vec::new();
let mut remaining = rule;
let mut used_names = HashSet::new();
while !remaining.is_empty() {
match rule_re.captures(remaining) {
Some(caps) => {
let static_part = caps.name("static");
if static_part.is_some() {
rule_parts.push((None, static_part.unwrap().as_str()));
}
let variable = caps.name("variable").unwrap();
let converter = match caps.name("converter") {
Some(converter) => { converter.as_str() },
None => { "default" },
};
if used_names.contains(variable.as_str()) {
panic!("variable name {} used twice.", variable.as_str());
}
used_names.insert(variable.as_str());
rule_parts.push((Some(converter), variable.as_str()));
let end = caps.get(0).unwrap().end();
let (_, tail) = remaining.split_at(end);
remaining = tail;
},
None => {
break;
}
}
}
if !remaining.is_empty() {
if remaining.contains('>') || remaining.contains('<') {
panic!("malformed url rule: {}", rule);
}
rule_parts.push((None, remaining));
}
rule_parts
}
#[derive(Clone, Debug)]
pub struct Matcher {
pub regex: Regex,
pub matches_query: bool,
}
impl Matcher {
pub fn new(regex: Regex, matches_query: bool) -> Matcher {
Matcher {
regex: regex,
matches_query: matches_query,
}
}
}
impl<'a> From<&'a str> for Matcher {
fn from(rule: &'a str) -> Matcher {
if !rule.starts_with('/') {
panic!("urls must start with a leading slash");
}
let matches_query = rule.contains('?');
let is_branch = rule.ends_with('/');
let mut regex_parts: Vec<String> = Vec::new();
for (converter, variable) in parse_rule(rule.trim_end_matches('/')) {
match converter {
Some(converter) => {
let re = match converter {
"string" | "default" => "[^/]{1,}",
"int" => r"\d+",
"float" => r"\d+\.\d+",
"path" => "[^/].*?",
_ => { panic!("the converter {} does not exist", converter); }
};
regex_parts.push(format!("(?P<{}>{})", variable, re));
},
None => {
let escaped_variable = regex_quote(variable);
regex_parts.push(escaped_variable);
}
}
}
if is_branch {
regex_parts.push(String::from("(?P<__suffix__>/?)"));
}
let regex = format!(r"^{}$", join_string(regex_parts, ""));
Matcher::new(Regex::new(®ex).unwrap(), matches_query)
}
}
impl From<String> for Matcher {
fn from(rule: String) -> Matcher {
let rule_str: &str = &rule;
rule_str.into()
}
}
impl From<Regex> for Matcher {
fn from(regex: Regex) -> Matcher {
Matcher::new(regex, false)
}
}
#[derive(Debug)]
pub struct RequestSlashError;
#[derive(Debug)]
pub enum MapAdapterMatched {
MatchedRule((Rule, ViewArgs)),
MatchedRedirect((String, u16)),
MatchedError(HTTPError)
}
#[derive(Clone, Debug)]
pub struct Rule {
pub matcher: Matcher,
pub methods: HashSet<Method>,
pub endpoint: String,
pub provide_automatic_options: bool,
}
impl Rule {
pub fn new(matcher: Matcher, methods: &[Method], endpoint: &str) -> Rule {
let mut all_methods = HashSet::new();
for method in methods.iter() {
all_methods.insert(method.clone());
}
if all_methods.contains(&Method::Get) {
all_methods.insert(Method::Head);
}
let provide_automatic_options = if all_methods.contains(&Method::Options) {
false
} else {
all_methods.insert(Method::Options);
true
};
Rule {
matcher: matcher,
endpoint: endpoint.to_string(),
methods: all_methods,
provide_automatic_options: provide_automatic_options,
}
}
pub fn matched(&self, path: &str) -> Option<Result<ViewArgs, RequestSlashError>> {
match self.matcher.regex.captures(&path) {
Some(caps) => {
if let Some(suffix) = caps.name("__suffix__") {
if suffix.as_str().is_empty() {
return Some(Err(RequestSlashError));
}
}
let mut view_args: HashMap<String, String> = HashMap::new();
for variable in self.matcher.regex.capture_names() {
if let Some(variable) = variable {
if variable != "__suffix__" {
view_args.insert(variable.to_owned(), caps.name(variable).unwrap().as_str().to_owned());
}
}
}
Some(Ok(view_args))
},
None => None,
}
}
}
#[derive(Clone, Debug)]
pub struct Map {
rules: Vec<Rule>,
}
impl Default for Map {
fn default() -> Map {
Map::new()
}
}
impl Map {
pub fn new() -> Map {
Map { rules: vec![] }
}
pub fn add(&mut self, rule: Rule) {
self.rules.push(rule);
}
pub fn bind(&self, host: String, path: String, query_string: Option<String>, method: Method) -> MapAdapter {
MapAdapter::new(self, host, path, query_string, method)
}
}
#[derive(Debug)]
pub struct MapAdapter<'m> {
map: &'m Map,
url_scheme: String,
host: String,
path: String,
query_string: Option<String>,
method: Method,
}
impl<'m> MapAdapter<'m> {
pub fn new(map: &Map, host: String, path: String, query_string: Option<String>, method: Method) -> MapAdapter {
MapAdapter {
map: map,
url_scheme: "http".to_owned(),
host: host,
path: path,
query_string: query_string,
method: method,
}
}
fn make_redirect_url(&self) -> String {
let mut redirect_path = String::from("");
redirect_path = redirect_path + &self.path.trim_start_matches('/') + "/";
let mut suffix = String::from("");
if let Some(ref query_string) = self.query_string {
suffix = suffix + "?" + query_string;
}
format!("{}://{}/{}{}", self.url_scheme, self.host, redirect_path, suffix)
}
pub fn matched(&self) -> MapAdapterMatched {
let mut have_match_for = HashSet::new();
for rule in &self.map.rules {
let rule_view_args: ViewArgs;
let matched = if rule.matcher.matches_query {
if let Some(ref query_string) = self.query_string {
rule.matched(&(self.path.to_string() + "?" + query_string))
} else {
rule.matched(&self.path)
}
} else {
rule.matched(&self.path)
};
match matched {
Some(result) => {
match result {
Ok(view_args) => {
rule_view_args = view_args;
},
Err(_) => {
let redirect_url = self.make_redirect_url();
return MapAdapterMatched::MatchedRedirect((redirect_url, 301));
}
}
},
None => { continue; },
}
if !rule.methods.contains(&self.method) {
for method in &rule.methods {
have_match_for.insert(method.clone());
}
continue;
}
return MapAdapterMatched::MatchedRule((rule.clone(), rule_view_args))
}
if !have_match_for.is_empty() {
let mut allowed_methods = Vec::new();
allowed_methods.extend(have_match_for.into_iter());
return MapAdapterMatched::MatchedError(MethodNotAllowed(Some(allowed_methods)))
}
MapAdapterMatched::MatchedError(NotFound)
}
pub fn allowed_methods(&self) -> Vec<Method> {
let mut have_match_for = HashSet::new();
for rule in &self.map.rules {
match rule.matched(&self.path) {
Some(_) => {
for method in &rule.methods {
have_match_for.insert(method.clone());
}
continue;
},
None => { continue; },
}
}
let mut allowed_methods = Vec::new();
allowed_methods.extend(have_match_for.into_iter());
allowed_methods
}
}
#[test]
fn test_basic_routing() {
let mut map = Map::new();
map.add(Rule::new("/".into(), &[Method::Get], "index"));
map.add(Rule::new("/foo".into(), &[Method::Get], "foo"));
map.add(Rule::new("/bar/".into(), &[Method::Get], "bar"));
let adapter = map.bind(String::from("localhost"), String::from("/bar/"), None, Method::Get);
match adapter.matched() {
MapAdapterMatched::MatchedRule((rule, view_args)) => {
assert!(rule.methods.contains(&Method::Get));
assert!(!rule.methods.contains(&Method::Post));
assert!(rule.endpoint == String::from("bar"));
assert!(view_args.len() == 0);
},
_ => { panic!("Basic routing failed!"); }
}
}