hyper_tree_router/
route.rs

1use super::parameters;
2use hyper::{Body, Method, Request, Response};
3use std::{collections::HashMap, fmt};
4
5pub type Handler = fn(parameters::UrlParams, Request<Body>) -> Response<Body>;
6
7// Holds route information
8#[derive(Clone)]
9pub struct Route {
10    /// Path to match
11    pub path: String,
12
13    /// Request handlers
14    pub handlers: HashMap<Method, Handler>,
15}
16
17impl Route {
18    /// Add handler for OPTIONS type requests
19    pub fn options(self, handler: Handler) -> Self {
20        self.using(Method::OPTIONS, handler)
21    }
22
23    /// Add handler for GET type requests
24    pub fn get(self, handler: Handler) -> Self {
25        self.using(Method::GET, handler)
26    }
27
28    /// Add handler for POST type requests
29    pub fn post(self, handler: Handler) -> Self {
30        self.using(Method::POST, handler)
31    }
32
33    /// Add handler for PUT type requests
34    pub fn put(self, handler: Handler) -> Self {
35        self.using(Method::PUT, handler)
36    }
37
38    /// Add handler for DELETE type requests
39    pub fn delete(self, handler: Handler) -> Self {
40        self.using(Method::DELETE, handler)
41    }
42
43    /// Add handler for HEAD type requests
44    pub fn head(self, handler: Handler) -> Self {
45        self.using(Method::HEAD, handler)
46    }
47
48    /// Add handler for TRACE type requests
49    pub fn trace(self, handler: Handler) -> Self {
50        self.using(Method::TRACE, handler)
51    }
52
53    /// Add handler for CONNECT type requests
54    pub fn connect(self, handler: Handler) -> Self {
55        self.using(Method::CONNECT, handler)
56    }
57
58    /// Add handler for PATCH type requests
59    pub fn patch(self, handler: Handler) -> Self {
60        self.using(Method::PATCH, handler)
61    }
62
63    /// Create `Route` for a given url
64    pub fn url(path: &str) -> Self {
65        Self {
66            path: path.to_string(),
67            ..Self::default()
68        }
69    }
70
71    fn using(mut self, method: Method, handler: Handler) -> Self {
72        self.handlers.insert(method, handler);
73        self
74    }
75}
76
77impl Default for Route {
78    fn default() -> Self {
79        Self {
80            path: "/".to_string(),
81            handlers: HashMap::new(),
82        }
83    }
84}
85
86impl fmt::Debug for Route {
87    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
88        write!(
89            f,
90            "Route {{methods: {:?}, path: {:?}}}",
91            self.handlers.keys(),
92            self.path
93        )
94    }
95}