-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathmacros.rs
78 lines (75 loc) · 2.42 KB
/
macros.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
/// Create and populate a router.
///
/// ```ignore
/// let router = router!(index: get "/" => index,
/// query: get "/:query" => queryHandler,
/// post: post "/" => postHandler);
/// ```
///
/// Is equivalent to:
///
/// ```ignore
/// let mut router = Router::new();
/// router.get("/", index, "index");
/// router.get("/:query", queryHandler, "query");
/// router.post("/", postHandler, "post");
/// ```
///
/// The method name must be lowercase, supported methods:
///
/// `get`, `post`, `put`, `delete`, `head`, `patch`, `options` and `any`.
#[macro_export]
macro_rules! router {
($($route_id:ident: $method:ident $glob:expr => $handler:expr),+ $(,)*) => ({
let mut router = $crate::Router::new();
$(router.$method($glob, $handler, stringify!($route_id));)*
router
});
}
/// Generate a URL based off of the requested one.
///
/// ```ignore
/// url_for!(request, "foo",
/// "query" => "test",
/// "extraparam" => "foo")
/// ```
///
/// Is equivalent to:
///
/// ```ignore
/// router::url_for(request, "foo", {
/// let mut rv = ::std::collections::HashMap::new();
/// rv.insert("query".to_owned(), "test".to_owned());
/// rv.insert("extraparam".to_owned(), "foo".to_owned());
/// rv
/// })
/// ```
#[macro_export]
macro_rules! url_for {
($request:expr, $route_id:expr $(,$key:expr => $value:expr)* $(,)*) => (
$crate::url_for($request, $route_id, {
// Underscore-prefix suppresses `unused_mut` warning
// Also works on stable rust!
let mut _params = ::std::collections::HashMap::<String, String>::new();
$(_params.insert($key.into(), $value.into());)*
_params
})
)
}
#[cfg(test)]
mod tests {
use iron::{Response, Request, IronResult};
//simple test to check that all methods expand without error
#[test]
fn methods() {
fn handler(_: &mut Request) -> IronResult<Response> {Ok(Response::new())}
let _ = router!(a: get "/foo" => handler,
b: post "/bar/" => handler,
c: put "/bar/baz" => handler,
d: delete "/bar/baz" => handler,
e: head "/foo" => handler,
f: patch "/bar/baz" => handler,
g: options "/foo" => handler,
h: any "/" => handler);
}
}