rouille/router.rs
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 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
// Copyright (c) 2016 The Rouille developers
// Licensed under the Apache License, Version 2.0
// <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT
// license <LICENSE-MIT or http://opensource.org/licenses/MIT>,
// at your option. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.
/// Equivalent to a `match` expression but for routes.
///
/// # Example
///
/// ```no_run
/// # #[macro_use] extern crate rouille; fn main() {
/// # let request: rouille::Request = unsafe { std::mem::uninitialized() };
/// let _result = router!(request,
/// // first route
/// (GET) (/) => {
/// 12
/// },
///
/// // second route
/// (GET) (/hello) => {
/// 43 * 7
/// },
///
/// // ... other routes here ...
///
/// // default route
/// _ => 5
/// );
/// # }
/// ```
///
/// # Details
///
/// The macro will take each route one by one and execute the first one that matches, similar to the
/// `match` language construct. The whole `router!` expression then returns what the body
/// returns, therefore all the bodies must return the same type of data.
///
/// You can use parameters by putting them inside `{}`:
///
/// ```ignore
/// (GET) (/{id}/foo) => {
/// ...
/// },
/// ```
///
/// If you use parameters inside `{}`, then a variable with the same name will be available in the
/// code in the body.
/// Each parameter gets parsed through the `FromStr` trait. If the parsing fails, the route is
/// ignored. If you get an error because the type of the parameter couldn't be inferred, you can
/// also specify the type inside the brackets:
///
/// ```ignore
/// (GET) (/{id: u32}/foo) => {
/// ...
/// },
/// ```
///
///
/// # Alternative syntax (**string-style**)
///
/// You can also define url routes using strings. This allows using characters that are not valid rust
/// `ident`s (e.g. periods and numbers).
///
/// ```ignore
/// (GET) ["/hello/2"] => { ... },
/// ```
///
/// You can use parameters by putting them inside `{}`, and adding an `identity: type` pair. Note
/// that `identity` names **must** match the parameter names used in the URL string and an
/// accompanying `type` is required. The declared identities (variables) will be parsed through the
/// `FromStr` trait and made available in the code of the route's body. If the parsing fails, the
/// route is ignored.
///
/// ```ignore
/// (GET) ["/add/{a}/plus/{b}", a: u32, b: u32] => {
/// let c = a + b;
/// ...
/// },
/// ```
///
/// # Some other things to note
///
/// - The right of the `=>` must be a block (must be surrounded by `{` and `}`).
/// - The default handler (with `_`) must be present or will get a compilation error.
/// - The pattern of the URL must be inside parentheses for ident-style syntax
/// and brackets for string-style syntax. This is to bypass limitations of Rust's macros system.
/// - String-style and token-style definitions are mutually exclusive. Either all routes are defined with
/// tokens or all routes are defined with strings.
/// - When using URL parameters with **string-style** syntax, the parameter names in the URL and `identity: type`
/// pairs must be the same, e.g. `... ["/users/{name}", name: String] ...` .
/// This can't be checked at compile time so bad route definitions will cause a runtime `panic`.
///
#[macro_export]
macro_rules! router {
// -----------------
// --- New style ---
// -----------------
($request:expr,
$(($method:ident) [$url_pattern:expr $(, $param:ident: $param_type:ty)*] => $handle:expr,)*
_ => $default:expr $(,)*) => {
{
let request = &$request;
// ignoring the GET parameters (everything after `?`)
let request_url = request.raw_url();
let request_url = {
let pos = request_url.find('?').unwrap_or(request_url.len());
&request_url[..pos]
};
let mut ret = None;
$({
if ret.is_none() && request.method() == stringify!($method) {
ret = $crate::router!(__param_dispatch request_url, $url_pattern => $handle ; $($param: $param_type),*);
}
})+
if let Some(ret) = ret {
ret
} else {
$default
}
}
};
// No url parameters, just check the url and evaluate the `$handle`
(__param_dispatch $request_url:ident, $url_pattern:expr => $handle:expr ; ) => {
$crate::router!(__check_url_match $request_url, $url_pattern => $handle)
};
// Url parameters found, check and parse the url against the provided pattern
(__param_dispatch $request_url:ident, $url_pattern:expr => $handle:expr ; $($param:ident: $param_type:ty),*) => {
$crate::router!(__check_parse_pattern $request_url, $url_pattern => $handle ; $($param: $param_type),*)
};
(__check_url_match $request_url:ident, $url_pattern:expr => $handle:expr) => {
if $request_url == $url_pattern {
Some($handle)
} else {
None
}
};
// Compare each url segment while attempting to parse any url parameters.
// If parsing fails, return `None` so this route gets skipped.
// If parsing is successful, recursively bind each url parameter to the given identity
// before evaluating the `$handle`
// Note: Url parameters need to be held in the `RouilleUrlParams` struct since
// we need to be able to "evaluate to None" (if url segments don't match or parsing fails)
// and we can't actually "return None" since we'd be returning from whatever scope the macro is being used in.
(__check_parse_pattern $request_url_str:ident, $url_pattern:expr => $handle:expr ; $($param:ident: $param_type:ty),*) => {
{
let request_url = $request_url_str.split("/")
.map(|s| $crate::percent_encoding::percent_decode(s.as_bytes()).decode_utf8_lossy().into_owned())
.collect::<Vec<_>>();
let url_pattern = $url_pattern.split("/").collect::<Vec<_>>();
if request_url.len() != url_pattern.len() {
None
} else {
struct RouilleUrlParams {
$( $param: Option<$param_type> ),*
}
impl RouilleUrlParams {
fn new() -> Self {
Self {
$( $param: None ),*
}
}
}
let url_params = (|| {
let mut url_params = RouilleUrlParams::new();
for (actual, desired) in request_url.iter().zip(url_pattern.iter()) {
if let Some(key) = desired.strip_prefix("{").and_then(|d| d.strip_suffix("}")) {
$crate::router!(__insert_param $request_url_str, url_params, key, actual ; $($param: $param_type)*)
} else if actual != desired {
return None
}
}
Some(url_params)
})();
if let Some(url_params) = url_params {
$crate::router!(__build_resp $request_url_str, url_params, $handle ; $($param: $param_type)*)
} else {
None
}
}
}
};
// We walked through all the given url parameter identities and couldn't find one that
// matches the parameter name defined in the url-string
// e.g. `(GET) ("/name/{title}", name: String)
(__insert_param $request_url:ident, $url_params:ident, $key:expr, $actual:expr ; ) => {
panic!("Unable to match url parameter name, `{}`, to an `identity: type` pair in url: {:?}", $key, $request_url);
};
// Walk through all the given url parameter identities. If they match the current
// `$key` (a parameter name in the string-url), then set them in the `$url_params` struct
(__insert_param $request_url:ident, $url_params:ident, $key:expr, $actual:expr ; $param:tt: $param_type:tt $($params:tt: $param_types:tt)*) => {
if $key == stringify!($param) {
$crate::router!(__bind_url_param $url_params, $actual, $param, $param_type)
} else {
$crate::router!(__insert_param $request_url, $url_params, $key, $actual ; $($params: $param_types)*);
}
};
(__bind_url_param $url_params:ident, $actual:expr, $param:ident, $param_type:ty) => {
{
match $actual.parse::<$param_type>() {
Ok(value) => $url_params.$param = Some(value),
// it's safe to `return` here since we're in a closure
Err(_) => return None,
}
}
};
// No more url parameters to bind
(__build_resp $request_url:ident, $url_params:expr, $handle:expr ; ) => {
{ Some($handle) }
};
// There's still some params to bind
(__build_resp $request_url:ident, $url_params:expr, $handle:expr ; $param:tt: $param_type:tt $($params:tt: $param_types:tt)*) => {
$crate::router!(__bind_param $request_url, $url_params, $handle, $param: $param_type ; $($params: $param_types)*)
};
// Recursively pull out and bind a url param
(__bind_param $request_url:ident, $url_params:expr, $handle:expr, $param:ident: $param_type:ty ; $($params:tt: $param_types:tt)*) => {
{
let $param = match $url_params.$param {
Some(p) => p,
None => {
let param_name = stringify!($param);
panic!("Url parameter identity, `{}`, does not have a matching `{{{}}}` segment in url: {:?}",
param_name, param_name, $request_url);
}
};
$crate::router!(__build_resp $request_url, $url_params, $handle ; $($params: $param_types)*)
}
};
// -----------------
// --- Old style ---
// -----------------
($request:expr, $(($method:ident) ($($pat:tt)+) => $value:block,)* _ => $def:expr $(,)*) => {
{
let request = &$request;
// ignoring the GET parameters (everything after `?`)
let request_url = request.raw_url();
let request_url = {
let pos = request_url.find('?').unwrap_or(request_url.len());
&request_url[..pos]
};
let mut ret = None;
$({
if ret.is_none() && request.method() == stringify!($method) {
ret = $crate::router!(__check_pattern request_url $value $($pat)+);
}
})+
if let Some(ret) = ret {
ret
} else {
$def
}
}
};
(__check_pattern $url:ident $value:block /{$p:ident} $($rest:tt)*) => (
if let Some(url) = $url.strip_prefix('/') {
let url = &$url[1..];
let pat_end = url.find('/').unwrap_or(url.len());
let rest_url = &url[pat_end..];
if let Ok($p) = url[0 .. pat_end].parse() {
$crate::router!(__check_pattern rest_url $value $($rest)*)
} else {
None
}
} else {
None
}
);
(__check_pattern $url:ident $value:block /{$p:ident: $t:ty} $($rest:tt)*) => (
if let Some(url) = $url.strip_prefix('/') {
let url = &$url[1..];
let pat_end = url.find('/').unwrap_or(url.len());
let rest_url = &url[pat_end..];
if let Ok($p) = $crate::percent_encoding::percent_decode(url[0 .. pat_end].as_bytes())
.decode_utf8_lossy().parse() {
let $p: $t = $p;
$crate::router!(__check_pattern rest_url $value $($rest)*)
} else {
None
}
} else {
None
}
);
(__check_pattern $url:ident $value:block /$p:ident $($rest:tt)*) => (
{
let required = concat!("/", stringify!($p));
if let Some(rest_url) = $url.strip_prefix(required) {
$crate::router!(__check_pattern rest_url $value $($rest)*)
} else {
None
}
}
);
(__check_pattern $url:ident $value:block - $($rest:tt)*) => (
{
if let Some(rest_url) = $url.strip_prefix('-') {
$crate::router!(__check_pattern rest_url $value $($rest)*)
} else {
None
}
}
);
(__check_pattern $url:ident $value:block) => (
if $url.len() == 0 { Some($value) } else { None }
);
(__check_pattern $url:ident $value:block /) => (
if $url == "/" { Some($value) } else { None }
);
(__check_pattern $url:ident $value:block $p:ident $($rest:tt)*) => (
{
let required = stringify!($p);
if let Some(rest_url) = $url.strip_prefix(required) {
$crate::router!(__check_pattern rest_url $value $($rest)*)
} else {
None
}
}
);
}
#[allow(unused_variables)]
#[cfg(test)]
mod tests {
use Request;
// -- old-style tests --
#[test]
fn old_style_basic() {
let request = Request::fake_http("GET", "/", vec![], vec![]);
assert_eq!(
1,
router!(request,
(GET) (/hello) => { 0 },
(GET) (/{_val:u32}) => { 0 },
(GET) (/) => { 1 },
_ => 0
)
);
}
#[test]
fn old_style_dash() {
let request = Request::fake_http("GET", "/a-b", vec![], vec![]);
assert_eq!(
1,
router!(request,
(GET) (/a/b) => { 0 },
(GET) (/a_b) => { 0 },
(GET) (/a-b) => { 1 },
_ => 0
)
);
}
#[test]
fn old_style_params() {
let request = Request::fake_http("GET", "/hello/5", vec![], vec![]);
assert_eq!(
1,
router!(request,
(GET) (/hello/) => { 0 },
(GET) (/hello/{id:u32}) => { if id == 5 { 1 } else { 0 } },
(GET) (/hello/{_id:String}) => { 0 },
_ => 0
)
);
}
#[test]
fn old_style_trailing_comma() {
let request = Request::fake_http("GET", "/hello/5", vec![], vec![]);
assert_eq!(
1,
router!(request,
(GET) (/hello/) => { 0 },
(GET) (/hello/{id:u32}) => { if id == 5 { 1 } else { 0 } },
(GET) (/hello/{_id:String}) => { 0 },
_ => 0,
)
);
}
#[test]
fn old_style_trailing_commas() {
let request = Request::fake_http("GET", "/hello/5", vec![], vec![]);
assert_eq!(
1,
router!(request,
(GET) (/hello/) => { 0 },
(GET) (/hello/{id:u32}) => { if id == 5 { 1 } else { 0 } },
(GET) (/hello/{_id:String}) => { 0 },
_ => 0,,,,
)
);
}
// -- new-style tests --
#[test]
fn multiple_params() {
let request = Request::fake_http("GET", "/math/3.2/plus/4", vec![], vec![]);
let resp = router!(request,
(GET) ["/hello"] => { 1. },
(GET) ["/math/{a}/plus/{b}", a: u32 , b: u32] => { 7. },
(GET) ["/math/{a}/plus/{b}", a: f32 , b: u32] => { a + (b as f32) },
_ => 0.
);
assert_eq!(7.2, resp);
}
#[test]
fn basic() {
let request = Request::fake_http("GET", "/", vec![], vec![]);
assert_eq!(
1,
router!(request,
(GET) ["/hello"] => { 0 },
(GET) ["/{_val}", _val: u32] => { 0 },
(GET) ["/"] => { 1 },
_ => 0
)
);
}
#[test]
fn dash() {
let request = Request::fake_http("GET", "/a-b", vec![], vec![]);
assert_eq!(
1,
router!(request,
(GET) ["/a/b"] => { 0 },
(GET) ["/a_b"] => { 0 },
(GET) ["/a-b"] => { 1 },
_ => 0
)
);
}
#[test]
fn numbers() {
let request = Request::fake_http("GET", "/5", vec![], vec![]);
assert_eq!(
1,
router!(request,
(GET) ["/a"] => { 0 },
(GET) ["/3"] => { 0 },
(GET) ["/5"] => { 1 },
_ => 0
)
);
}
#[test]
fn trailing_comma() {
let request = Request::fake_http("GET", "/5", vec![], vec![]);
assert_eq!(
1,
router!(request,
(GET) ["/a"] => { 0 },
(GET) ["/3"] => { 0 },
(GET) ["/5"] => { 1 },
_ => 0,
)
);
}
#[test]
fn trailing_commas() {
let request = Request::fake_http("GET", "/5", vec![], vec![]);
assert_eq!(
1,
router!(request,
(GET) ["/a"] => { 0 },
(GET) ["/3"] => { 0 },
(GET) ["/5"] => { 1 },
_ => 0,,,,
)
);
}
#[test]
fn files() {
let request = Request::fake_http("GET", "/robots.txt", vec![], vec![]);
assert_eq!(
1,
router!(request,
(GET) ["/a"] => { 0 },
(GET) ["/3/2/1"] => { 0 },
(GET) ["/robots.txt"] => { 1 },
_ => 0
)
);
}
#[test]
fn skip_failed_parse_float() {
let request = Request::fake_http("GET", "/hello/5.1", vec![], vec![]);
assert_eq!(
1,
router!(request,
(GET) ["/hello/"] => { 0 },
(GET) ["/hello/{_id}", _id: u32] => { 0 },
(GET) ["/hello/{id}", id: f32] => { if id == 5.1 { 1 } else { 0 } },
_ => 0
)
);
}
#[test]
fn skip_failed_parse_string() {
let request = Request::fake_http("GET", "/word/wow", vec![], vec![]);
let resp = router!(request,
(GET) ["/hello"] => { "hello".to_string() },
(GET) ["/word/{int}", int: u32] => { int.to_string() },
(GET) ["/word/{word}", word: String] => { word },
_ => "default".to_string()
);
assert_eq!("wow", resp);
}
#[test]
fn url_parameter_ownership() {
let request = Request::fake_http("GET", "/word/one/two/three/four", vec![], vec![]);
let resp = router!(request,
(GET) ["/hello"] => { "hello".to_string() },
(GET) ["/word/{int}", int: u32] => { int.to_string() },
(GET) ["/word/{a}/{b}/{c}/{d}", a: String, b: String, c: String, d: String] => {
fn expects_strings(a: String, b: String, c: String, d: String) -> String {
format!("{}{}{}{}", a, b, c, d)
}
expects_strings(a, b, c, d)
},
_ => "default".to_string()
);
assert_eq!("onetwothreefour", resp);
}
#[test]
#[should_panic(
expected = "Url parameter identity, `id`, does not have a matching `{id}` segment in url: \"/hello/james\""
)]
fn identity_not_present_in_url_string() {
let request = Request::fake_http("GET", "/hello/james", vec![], vec![]);
assert_eq!(
1,
router!(request,
(GET) ["/hello/"] => { 0 },
(GET) ["/hello/{name}", name: String, id: u32] => { 1 }, // this should fail
_ => 0
)
);
}
#[test]
#[should_panic(
expected = "Unable to match url parameter name, `name`, to an `identity: type` pair in url: \"/hello/1/james\""
)]
fn parameter_with_no_matching_identity() {
let request = Request::fake_http("GET", "/hello/1/james", vec![], vec![]);
assert_eq!(
1,
router!(request,
(GET) ["/hello/"] => { 0 },
(GET) ["/hello/{id}/{name}"] => { 0 }, // exact match should be ignored
(GET) ["/hello/{id}/{name}", id: u32] => { id }, // this one should fail
_ => 0
)
);
}
#[test]
fn encoded() {
let request = Request::fake_http("GET", "/hello/%3Fa/test", vec![], vec![]);
assert_eq!(
"?a",
router!(request,
(GET) ["/hello/{val}/test", val: String] => { val },
_ => String::from(""))
);
}
#[test]
fn encoded_old() {
let request = Request::fake_http("GET", "/hello/%3Fa/test", vec![], vec![]);
assert_eq!(
"?a",
router!(request,
(GET) (/hello/{val: String}/test) => { val },
_ => String::from(""))
);
}
#[test]
fn param_slash() {
let request = Request::fake_http("GET", "/hello%2F5", vec![], vec![]);
router!(request,
(GET) ["/{a}", a: String] => { assert_eq!(a, "hello/5") },
_ => panic!()
);
}
}