tower_web/routing/
route.rs

1use super::{Captures, Path};
2
3use http::{Method, Request};
4
5/// Matches an HTTP request with a resource method.
6#[derive(Debug)]
7pub struct Route<T> {
8    /// Where to route the request
9    destination: T,
10
11    /// HTTP method used to match the route
12    method: Method,
13
14    /// Path used to match the route
15    path: Path,
16}
17
18impl<T> Route<T> {
19    /// Create a new route
20    pub fn new(destination: T) -> Self {
21        let method = Method::default();
22        let path = Path::new("/");
23
24        Route {
25            destination,
26            method,
27            path,
28        }
29    }
30
31    /// Set the HTTP request method matched by this route.
32    pub fn method(mut self, value: Method) -> Self {
33        self.method = value;
34        self
35    }
36
37    /// Set the HTTP request path matched by this route.
38    pub fn path(mut self, path: &str) -> Self {
39        self.path = Path::new(path);
40        self
41    }
42
43    pub(crate) fn map<F, U>(self, f: F) -> Route<U>
44    where
45        F: Fn(T) -> U,
46    {
47        let destination = f(self.destination);
48
49        Route {
50            destination,
51            method: self.method,
52            path: self.path,
53        }
54    }
55}
56
57impl<T> Route<T>
58where
59    T: Clone,
60{
61    /// Try to match a request against this route.
62    pub(crate) fn test<'a>(
63        &'a self,
64        request: &Request<()>,
65    ) -> Option<(T, Captures)> {
66
67        if *request.method() != self.method {
68            return None;
69        }
70
71        self.path.test(request.uri().path())
72            .map(|captures| {
73                (self.destination.clone(), captures)
74            })
75    }
76}