match_request 0.1.0

Macros for creating request routers in hyper.
Documentation
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
//! Macros for creating request routers in hyper.
//!
//! Request paths can be matched using a more convenient readable syntax,
//! or using full regular expressions. Specific methods can be listed
//! under each path.
//!
//! The return value of a match can be anything, though you'll usually
//! want to return a boxed function to use as a view.
//!
//!
//! # Pattern syntax
//!
//! Matching a request path:
//!
//! ```
//! use match_request::match_request;
//! use hyper::Method;
//!
//! let path = "/user/home";
//! let (value, params) = match_request!(&Method::GET, path, {
//!     "/login" => {
//!         GET => "serve login form",
//!     },
//!     "/user/home" => {
//!         GET => "serve home page",
//!     }
//! }).unwrap();
//!
//! assert_eq!(value, "serve home page");
//! ```
//!
//! Matching against multiple methods:
//!
//! ```
//! use match_request::match_request;
//! use hyper::Method;
//!
//! let path = "/example";
//! let (value, params) = match_request!(&Method::DELETE, path, {
//!     "/login" => {
//!         GET => "serve login form",
//!         POST => "attempt login",
//!     },
//!     "/example" => {
//!         GET => "serve example page",
//!         DELETE => "delete example page",
//!     }
//! }).unwrap();
//!
//! assert_eq!(value, "delete example page");
//! ```
//!
//! Named path parameters:
//!
//! ```
//! use match_request::match_request;
//! use hyper::Method;
//!
//! let path = "/posts/2020/my-blog-post";
//! let (value, params) = match_request!(&Method::GET, path, {
//!     "/posts/:year/:slug" => {
//!         GET => "serve blog post",
//!     },
//! }).unwrap();
//!
//! assert_eq!(params.get("year"), Some("2020"));
//! assert_eq!(params.get("slug"), Some("my-blog-post"));
//! ```
//!
//! Capturing the path tail:
//!
//! ```
//! use match_request::match_request;
//! use hyper::Method;
//!
//! let path = "/static/vendor/img/icon.png";
//! let (value, params) = match_request!(&Method::GET, path, {
//!     "/static/*" => {
//!         GET => "serve static assets",
//!     },
//! }).unwrap();
//!
//! // NOTE: the leading `/` is included
//! assert_eq!(params.tail(), Some("/vendor/img/icon.png"));
//! ```
//!
//! # Example router
//!
//! ```
//! use match_request::{match_request, Error, Params};
//! use hyper::{Request, Response, Body};
//! use futures::future::{Future, BoxFuture};
//!
//! // A boxed type definition for your async views.
//! type BoxedView = Box<
//!     dyn Fn(Request<Body>, Params) ->
//!     BoxFuture<'static, Response<Body>>
//! >;
//!
//! // Like a regular `match` expression, `match_request` requires all
//! // arms to return the same type. As each `async fn` will have a different
//! // type, you'll likely need to put them in a Box first. This example macro
//! // is one way to do it.
//! macro_rules! view {
//!     ($closure:expr) => {{
//!         #[allow(unused_mut)]
//!         let mut closure = $closure;
//!         let b: BoxedView = Box::new(move |req, params| {
//!             Box::pin(closure(req, params))
//!         });
//!         b
//!     }};
//! }
//!
//! // An example request router.
//! async fn router(req: Request<Body>) -> Result<Response<Body>, Error> {
//!     let method = req.method();
//!     let path = req.uri().path();
//!
//!     // Attempt to match the request to a view.
//!     let (handler, params) = match_request!(method, path, {
//!         "/foo/bar" => {
//!             GET => view!(foo_bar),
//!         },
//!         "/user/:name" => {
//!             GET => view!(user_profile),
//!         }
//!     })?;
//!
//!     // Execute the view.
//!     Ok(handler(req, params).await)
//! }
//!
//! // Example views...
//!
//! async fn foo_bar(_req: Request<Body>, _params: Params) -> Response<Body> {
//!     Response::new(Body::from("Foo bar"))
//! }
//!
//! async fn user_profile(_req: Request<Body>, params: Params) -> Response<Body> {
//!     // Extracting a parameter from the path.
//!     let name = params.get("name").unwrap();
//!     Response::new(Body::from(format!("Profile for {}", name)))
//! }
//! ```

#[doc(hidden)]
pub use lazy_static;
#[doc(hidden)]
pub use regex::{Regex, Captures};
#[doc(hidden)]
pub use hyper::Method;

use std::fmt;
use std::collections::BTreeMap;

/// Possible failures for the `match_request` and
/// `match_request_regex` macros.
#[derive(Debug, PartialEq)]
pub enum Error {
    /// The path did not match any patterns.
    NotFound,
    /// The path matched a pattern, but the pattern had no matching
    /// arm for the given HTTP method.
    MethodNotAllowed,
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", match self {
            &Error::NotFound => "Not found",
            &Error::MethodNotAllowed => "Method not allowed",
        })
    }
}

impl std::error::Error for Error {}

/// Converts a URL pattern to a String suitable for compilation as a
/// regular expression.
pub fn pattern(src: &str) -> String {
    use lazy_static::lazy_static;
    lazy_static! {
        static ref TAIL: Regex = Regex::new(r"^\\\*|/\\\*").unwrap();
        static ref NAMED: Regex = Regex::new(
            ":([0-9a-zA-Z][_0-9a-zA-Z]*)"
        ).unwrap();
    }
    let dest = regex::escape(src);
    let dest = TAIL.replace(&dest, "(?P<__tail__>/.*)");
    let dest = NAMED.replace_all(&dest, |caps: &Captures| {
        format!("(?P<{}>[^/]+)", &caps[1])
    });
    format!("^{}$", dest)
}

/// Parameters matched by a URL pattern.
#[derive(Debug, Clone)]
pub struct Params {
    named: BTreeMap<String, String>,
    tail: Option<String>,
}

impl Params {
    /// Gets a named parameter from the matched pattern.
    ///
    /// For example, the pattern `/post/:id` would produce a named
    /// parameter that can be retrieved using `get("id")`.
    pub fn get<'a>(&'a self, name: &str) -> Option<&'a str> {
        self.named.get(name).map(|s| &s[..])
    }

    /// If the pattern included `/*`, this is the rest of the path
    /// from that point (including the leading forward-slash).
    ///
    /// For example, the path `/foo/bar` applied to the pattern
    /// `/foo/*` would result in a tail() value of `Some("/bar")`). If
    /// the pattern did not include `/*`, this method returns None.
    pub fn tail(&self) -> Option<&str> {
        self.tail.as_ref().map(|s| &s[..])
    }

    /// The total number of matched parameters (including the tail, if
    /// any).
    pub fn len(&self) -> usize {
        self.named.len() + (if self.tail.is_some() { 1 } else { 0 })
    }

    /// Returns true if the pattern matched no named parameters and no
    /// tail, false otherwise.
    pub fn is_empty(&self) -> bool {
        self.named.is_empty() && self.tail.is_none()
    }

    /// Creates a Params struct from the provided Regex capture names
    /// and matches (the tail capture should be named "\_\_tail\_\_").
    ///
    /// You should not need to call this directly.
    pub fn from_captures<'t>(
        names: regex::CaptureNames,
        caps: Captures<'t>
    ) -> Self {
        let mut named = BTreeMap::new();
        let mut tail = None;
        for (name, value) in names.zip(caps.iter()) {
            match name {
                Some("__tail__") => {
                    tail = value.map(|s| s.as_str().to_string());
                },
                Some(name) => {
                    if let Some(value) = value {
                        named.insert(
                            name.to_string(),
                            value.as_str().to_string()
                        );
                    }
                },
                None => (),
            }
        }
        Params { named, tail }
    }
}

/// Matches a request method and path against the provided patterns,
/// returning the matched value (if any) and any captured parameters
/// from the path.
///
/// # Returns
///
/// `Result<(T, match_request::Params), match_request::Error>` where
/// `T` is the type of the match arms.
#[macro_export]
macro_rules! match_request {
    ($request_method:expr, $request_path:expr, {
        $($pattern:literal => {
            $($method:ident => $result:expr),* $(,)?
        }),* $(,)?
    }) => {{
        let result = $crate::_match_request_regex!(
            $request_method,
            $request_path,
            {
                $($crate::pattern($pattern) => {
                    $($method => $result),*
                }),*
            }
        );
        result.map(move |(value, names, captures)| {
            (value, $crate::Params::from_captures(
                names,
                captures
            ))
        })
    }};
}

/// Like `match_request!` but each pattern is a raw Regex pattern. If
/// you want to match entire URLs be sure to prefix each pattern with
/// `^` and end with `$` as no conversion is made before passing the
/// pattern to `Regexp::new()` for compilation.
///
/// Intstead of returning a Params struct with the match path
/// parameters, this macro will return the raw regexp::Captures.
///
/// # Returns
///
/// `Result<(T, regex::Captures<'t>), match_request::Error>` where `T`
/// is the type of the match arms, and the lifetime `'t` relates to
/// the provided `path` argument.
///
/// # Panics
///
/// If any of the regular expressions are invalid this macro will
/// panic on first invocation.
#[macro_export]
macro_rules! match_request_regex {
    ($request_method:expr, $request_path:expr, {
        $($pattern:expr => {
            $($method:ident => $result:expr),* $(,)?
        }),* $(,)?
    }) => {{
        let result = $crate::_match_request_regex!(
            $request_method,
            $request_path,
            {$($pattern => {$($method => $result),*}),*}
        );
        result.map(move |(value, _names, captures)| {
            (value, captures)
        })
    }};
}

#[doc(hidden)]
#[macro_export]
macro_rules! _match_request_regex {
    ($request_method:expr, $request_path:expr, {
        $($pattern:expr => {
            $($method:ident => $value:expr),* $(,)?
        }),* $(,)?
    }) => {{
        use $crate::{Error, Regex, Method};
        use $crate::lazy_static::lazy_static;
        let path = $request_path;
        let method = $request_method;
        loop {
            $({
                lazy_static! {
                    static ref RE: Regex = Regex::new(
                        $pattern.as_ref()
                    ).unwrap();
                }
                if let Some(captures) = RE.captures(path) {
                    match method {
                        $(&Method::$method => {
                            break Ok((
                                $value,
                                RE.capture_names(),
                                captures,
                            ));
                        },)*
                        _ => {
                            break Err(Error::MethodNotAllowed);
                        },
                    }
                }
            };)*
            break Err(Error::NotFound);
        }
    }};
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn match_exact_path() {
        let result = match_request!(&Method::GET, "/bar", {
            "/foo" => {
                GET => 111
            },
            "/bar" => {
                GET => 222
            },
            "/baz" => {
                GET => 333
            }
        });
        let (value, params) = result.unwrap();
        assert!(params.is_empty());
        assert_eq!(params.len(), 0);
        assert_eq!(value, 222);
    }

    #[test]
    fn match_method() {
        let result = match_request!(&Method::PUT, "/foo", {
            "/foo" => {
                GET => 111,
                POST => 123,
                PUT => 456,
                DELETE => 789
            },
            "/bar" => {
                GET => 222
            },
            "/baz" => {
                GET => 333
            }
        });
        let (value, params) = result.unwrap();
        assert!(params.is_empty());
        assert_eq!(params.len(), 0);
        assert_eq!(value, 456);
    }

    #[test]
    fn no_matching_path() {
        let result = match_request!(&Method::GET, "/asdf", {
            "/foo" => {
                GET => 111,
            },
            "/bar" => {
                GET => 222
            },
            "/baz" => {
                GET => 333
            }
        });
        assert_eq!(result.unwrap_err(), Error::NotFound);

    }

    #[test]
    fn no_matching_method() {
        let result = match_request!(&Method::DELETE, "/foo", {
            "/foo" => {
                GET => 111,
                POST => 123,
                PUT => 456,
            },
            "/bar" => {
                GET => 222,
            },
            "/baz" => {
                GET => 333,
            },
        });
        assert_eq!(result.unwrap_err(), Error::MethodNotAllowed);
    }

    #[test]
    fn match_named_params() {
        let result = match_request!(&Method::GET, "/user/11/articles/foo-bar", {
            "/user/:id/articles/:slug" => {
                GET => 123
            },
        });
        let (value, params) = result.unwrap();
        assert_eq!(params.get("id").unwrap(), "11");
        assert_eq!(params.get("slug").unwrap(), "foo-bar");
        assert_eq!(params.len(), 2);
        assert!(!params.is_empty());
        assert_eq!(value, 123);
    }

    #[test]
    fn tail_capture_includes_leading_forward_slash() {
        let result = match_request!(&Method::GET, "/user/11/articles/foo-bar", {
            "/user/*" => {
                GET => 123
            },
        });
        let (value, params) = result.unwrap();
        assert_eq!(params.tail().unwrap(), "/11/articles/foo-bar");
        assert_eq!(params.len(), 1);
        assert_eq!(value, 123);
    }

    #[test]
    fn capture_entire_path() {
        let result = match_request!(&Method::GET, "/user/11/articles/foo-bar", {
            "/foo/bar" => {
                GET => 111,
            },
            "*" => {
                GET => 123,
            },
        });
        let (value, params) = result.unwrap();
        assert_eq!(params.tail().unwrap(), "/user/11/articles/foo-bar");
        assert_eq!(params.len(), 1);
        assert_eq!(value, 123);
    }

    #[test]
    fn pattern_must_match_full_path() {
        let result = match_request!(&Method::GET, "/foo/bar", {
            "/bar" => {
                GET => 123
            },
            "/foo" => {
                GET => 456
            },
        });
        assert_eq!(result.unwrap_err(), Error::NotFound);
    }

    #[test]
    fn regex_capture_groups() {
        let result = match_request_regex!(&Method::GET, "/user/11/articles/foo-bar", {
            r"^/user/(\d+)/articles/([a-z-]+)$" => {
                GET => 123
            },
        });
        let (value, captures) = result.unwrap();
        assert_eq!(captures.get(0).unwrap().as_str(), "/user/11/articles/foo-bar");
        assert_eq!(captures.get(1).unwrap().as_str(), "11");
        assert_eq!(captures.get(2).unwrap().as_str(), "foo-bar");
        assert_eq!(captures.len(), 3);
        assert_eq!(value, 123);
    }

}