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
use super::{Captures, Path};

use http::{Method, Request};

/// Matches an HTTP request with a resource method.
#[derive(Debug)]
pub struct Route<T> {
    /// Where to route the request
    destination: T,

    /// HTTP method used to match the route
    method: Method,

    /// Path used to match the route
    path: Path,
}

impl<T> Route<T> {
    /// Create a new route
    pub fn new(destination: T) -> Self {
        let method = Method::default();
        let path = Path::new("/");

        Route {
            destination,
            method,
            path,
        }
    }

    /// Set the HTTP request method matched by this route.
    pub fn method(mut self, value: Method) -> Self {
        self.method = value;
        self
    }

    /// Set the HTTP request path matched by this route.
    pub fn path(mut self, path: &str) -> Self {
        self.path = Path::new(path);
        self
    }

    pub(crate) fn map<F, U>(self, f: F) -> Route<U>
    where
        F: Fn(T) -> U,
    {
        let destination = f(self.destination);

        Route {
            destination,
            method: self.method,
            path: self.path,
        }
    }
}

impl<T> Route<T>
where
    T: Clone,
{
    /// Try to match a request against this route.
    pub(crate) fn test<'a>(
        &'a self,
        request: &Request<()>,
    ) -> Option<(T, Captures)> {

        if *request.method() != self.method {
            return None;
        }

        self.path.test(request.uri().path())
            .map(|captures| {
                (self.destination.clone(), captures)
            })
    }
}