Skip to main content

ruest/router/
registry.rs

1use super::{HttpMethod, RouteDefinition};
2
3/// Collects route definitions before they are mounted on the HTTP server.
4#[derive(Default, Clone)]
5pub struct RouteRegistry {
6    routes: Vec<RouteDefinition>,
7    global_prefix: Option<String>,
8}
9
10impl RouteRegistry {
11    pub fn new() -> Self {
12        Self::default()
13    }
14
15    pub fn set_global_prefix(&mut self, prefix: impl Into<String>) {
16        self.global_prefix = Some(prefix.into());
17    }
18
19    pub fn register(&mut self, route: RouteDefinition) {
20        self.routes.push(route);
21    }
22
23    pub fn register_many(&mut self, routes: impl IntoIterator<Item = RouteDefinition>) {
24        self.routes.extend(routes);
25    }
26
27    pub fn routes(&self) -> &[RouteDefinition] {
28        &self.routes
29    }
30
31    pub fn resolve_path(&self, path: &str) -> String {
32        match &self.global_prefix {
33            Some(prefix) => {
34                let prefix = prefix.trim_end_matches('/');
35                let path = if path.starts_with('/') {
36                    path.to_string()
37                } else {
38                    format!("/{path}")
39                };
40                format!("{prefix}{path}")
41            }
42            None => {
43                if path.starts_with('/') {
44                    path.to_string()
45                } else {
46                    format!("/{path}")
47                }
48            }
49        }
50    }
51
52    pub fn find(&self, method: HttpMethod, path: &str) -> Option<&RouteDefinition> {
53        self.routes
54            .iter()
55            .find(|r| r.method == method && r.path == path)
56    }
57}