Skip to main content

rustio_core/
router.rs

1//! Path router with `:param` support.
2//!
3//! Routes are registered against a [`Router`] and dispatched by path +
4//! method. Paths that match but with the wrong method produce `405 Method
5//! Not Allowed` rather than collapsing to `404`.
6
7use std::future::Future;
8use std::pin::Pin;
9use std::sync::Arc;
10
11use hyper::Method;
12
13use crate::error::Error;
14use crate::http::{Request, Response};
15use crate::middleware::{MiddlewareFn, Next};
16
17type BoxFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
18type HandlerFn = Arc<dyn Fn(Request, Params) -> BoxFuture<Result<Response, Error>> + Send + Sync>;
19
20pub struct Params {
21    pairs: Vec<(String, String)>,
22}
23
24impl Params {
25    fn empty() -> Self {
26        Self { pairs: Vec::new() }
27    }
28
29    pub fn get(&self, name: &str) -> Option<&str> {
30        self.pairs
31            .iter()
32            .find_map(|(k, v)| (k == name).then_some(v.as_str()))
33    }
34
35    pub fn len(&self) -> usize {
36        self.pairs.len()
37    }
38
39    pub fn is_empty(&self) -> bool {
40        self.pairs.is_empty()
41    }
42}
43
44enum Segment {
45    Literal(String),
46    Param(String),
47}
48
49struct Route {
50    method: Method,
51    segments: Vec<Segment>,
52    handler: HandlerFn,
53}
54
55pub struct Router {
56    routes: Vec<Route>,
57    middlewares: Vec<MiddlewareFn>,
58}
59
60impl Router {
61    pub fn new() -> Self {
62        Self {
63            routes: Vec::new(),
64            middlewares: Vec::new(),
65        }
66    }
67
68    pub fn wrap<F, Fut>(mut self, middleware: F) -> Self
69    where
70        F: Fn(Request, Next) -> Fut + Send + Sync + 'static,
71        Fut: Future<Output = Result<Response, Error>> + Send + 'static,
72    {
73        self.middlewares
74            .push(Arc::new(move |req, next| Box::pin(middleware(req, next))));
75        self
76    }
77
78    pub fn get<F, Fut>(self, path: &str, handler: F) -> Self
79    where
80        F: Fn(Request, Params) -> Fut + Send + Sync + 'static,
81        Fut: Future<Output = Result<Response, Error>> + Send + 'static,
82    {
83        self.route(Method::GET, path, handler)
84    }
85
86    pub fn post<F, Fut>(self, path: &str, handler: F) -> Self
87    where
88        F: Fn(Request, Params) -> Fut + Send + Sync + 'static,
89        Fut: Future<Output = Result<Response, Error>> + Send + 'static,
90    {
91        self.route(Method::POST, path, handler)
92    }
93
94    fn route<F, Fut>(mut self, method: Method, path: &str, handler: F) -> Self
95    where
96        F: Fn(Request, Params) -> Fut + Send + Sync + 'static,
97        Fut: Future<Output = Result<Response, Error>> + Send + 'static,
98    {
99        let handler: HandlerFn = Arc::new(move |req, params| Box::pin(handler(req, params)));
100        self.routes.push(Route {
101            method,
102            segments: parse_path(path),
103            handler,
104        });
105        self
106    }
107
108    pub async fn dispatch(&self, req: Request) -> Response {
109        let path = req.uri().path().to_owned();
110        let actual: Vec<&str> = path.split('/').filter(|s| !s.is_empty()).collect();
111        let method = req.method().clone();
112
113        let mut found: Option<(HandlerFn, Params)> = None;
114        let mut path_matched = false;
115
116        for route in &self.routes {
117            if let Some(params) = match_segments(&route.segments, &actual) {
118                path_matched = true;
119                if route.method == method {
120                    found = Some((route.handler.clone(), params));
121                    break;
122                }
123            }
124        }
125
126        let (handler, params) = found.unwrap_or_else(|| {
127            let method_not_allowed = path_matched;
128            let fallback: HandlerFn = Arc::new(move |_req, _params| {
129                let err = if method_not_allowed {
130                    Error::MethodNotAllowed
131                } else {
132                    Error::NotFound
133                };
134                Box::pin(async move { Err(err) })
135            });
136            (fallback, Params::empty())
137        });
138
139        let chain = build_chain(&self.middlewares, handler, params);
140        match chain(req).await {
141            Ok(resp) => resp,
142            Err(err) => err.into_response(),
143        }
144    }
145}
146
147impl Default for Router {
148    fn default() -> Self {
149        Self::new()
150    }
151}
152
153fn build_chain(
154    middlewares: &[MiddlewareFn],
155    handler: HandlerFn,
156    params: Params,
157) -> Box<dyn FnOnce(Request) -> BoxFuture<Result<Response, Error>> + Send> {
158    let mut chain: Box<dyn FnOnce(Request) -> BoxFuture<Result<Response, Error>> + Send> =
159        Box::new(move |req| handler(req, params));
160
161    for mw in middlewares.iter().rev() {
162        let mw = mw.clone();
163        let inner = chain;
164        chain = Box::new(move |req| {
165            let next = Next::new(inner);
166            mw(req, next)
167        });
168    }
169    chain
170}
171
172fn parse_path(path: &str) -> Vec<Segment> {
173    path.split('/')
174        .filter(|s| !s.is_empty())
175        .map(|s| match s.strip_prefix(':') {
176            Some(name) => Segment::Param(name.to_owned()),
177            None => Segment::Literal(s.to_owned()),
178        })
179        .collect()
180}
181
182fn match_segments(patterns: &[Segment], actual: &[&str]) -> Option<Params> {
183    if patterns.len() != actual.len() {
184        return None;
185    }
186    let mut params = Params::empty();
187    for (pat, seg) in patterns.iter().zip(actual.iter()) {
188        match pat {
189            Segment::Literal(lit) => {
190                if lit != seg {
191                    return None;
192                }
193            }
194            Segment::Param(name) => {
195                params.pairs.push((name.clone(), (*seg).to_owned()));
196            }
197        }
198    }
199    Some(params)
200}
201
202#[cfg(test)]
203mod tests {
204    use super::*;
205
206    fn segs(path: &str) -> Vec<Segment> {
207        parse_path(path)
208    }
209
210    fn parts(path: &str) -> Vec<&str> {
211        path.split('/').filter(|s| !s.is_empty()).collect()
212    }
213
214    #[test]
215    fn root_path_is_empty_segment_list() {
216        assert!(parse_path("/").is_empty());
217    }
218
219    #[test]
220    fn literal_match() {
221        assert!(match_segments(&segs("/users"), &parts("/users")).is_some());
222        assert!(match_segments(&segs("/users"), &parts("/posts")).is_none());
223    }
224
225    #[test]
226    fn param_captures_value() {
227        let params = match_segments(&segs("/users/:id"), &parts("/users/42")).unwrap();
228        assert_eq!(params.get("id"), Some("42"));
229    }
230
231    #[test]
232    fn length_mismatch_does_not_match() {
233        assert!(match_segments(&segs("/users/:id"), &parts("/users")).is_none());
234        assert!(match_segments(&segs("/users"), &parts("/users/42")).is_none());
235    }
236
237    #[test]
238    fn multiple_params_captured_by_name() {
239        let params = match_segments(&segs("/a/:x/b/:y"), &parts("/a/first/b/second")).unwrap();
240        assert_eq!(params.get("x"), Some("first"));
241        assert_eq!(params.get("y"), Some("second"));
242    }
243}