Skip to main content

serenade_http/
matcher.rs

1//! Path and method matching against a [`crate::RouteCollection`].
2
3use std::collections::HashMap;
4
5use crate::{HttpError, Method, RouteCollection};
6
7/// Attribute key written by [`UrlMatcher::apply`] for the matched route name.
8pub const ROUTE_ATTRIBUTE: &str = "_route";
9
10/// Successful match: route name plus path parameters.
11#[derive(Clone, Debug, Eq, PartialEq)]
12pub struct MatchResult {
13    route_name: String,
14    parameters: HashMap<String, String>,
15}
16
17impl MatchResult {
18    /// Matched route name.
19    #[must_use]
20    pub fn route_name(&self) -> &str {
21        &self.route_name
22    }
23
24    /// Captured path parameters.
25    #[must_use]
26    pub const fn parameters(&self) -> &HashMap<String, String> {
27        &self.parameters
28    }
29}
30
31/// Matches request method and path against a [`RouteCollection`].
32#[derive(Clone, Debug, Default)]
33pub struct UrlMatcher {
34    collection: RouteCollection,
35}
36
37impl UrlMatcher {
38    /// Matcher over `collection`.
39    #[must_use]
40    pub const fn new(collection: RouteCollection) -> Self {
41        Self { collection }
42    }
43
44    /// Underlying collection.
45    #[must_use]
46    pub const fn collection(&self) -> &RouteCollection {
47        &self.collection
48    }
49
50    /// Finds the first route whose path matches and that allows `method`.
51    ///
52    /// # Errors
53    ///
54    /// - Status **404** when no path matches.
55    /// - Status **405** when a path matches but the method is not allowed.
56    pub fn match_request(&self, method: Method, path: &str) -> Result<MatchResult, HttpError> {
57        let mut path_matched = false;
58        for route in self.collection.routes() {
59            let Some(parameters) = match_path(route.path(), path) else {
60                continue;
61            };
62            path_matched = true;
63            if route.allows(method) {
64                return Ok(MatchResult {
65                    route_name: route.name().to_owned(),
66                    parameters,
67                });
68            }
69        }
70        if path_matched {
71            Err(HttpError::status(
72                405,
73                format!("method `{method}` not allowed"),
74            ))
75        } else {
76            Err(HttpError::status(404, format!("no route for `{path}`")))
77        }
78    }
79
80    /// Writes `_route` and path parameters onto `request` attributes.
81    ///
82    /// # Errors
83    ///
84    /// Propagates [`Self::match_request`] errors.
85    pub fn apply(&self, request: &mut crate::Request) -> Result<MatchResult, HttpError> {
86        let matched = self.match_request(request.method(), request.path())?;
87        request
88            .attributes_mut()
89            .insert(ROUTE_ATTRIBUTE, matched.route_name().to_owned());
90        for (key, value) in matched.parameters() {
91            request.attributes_mut().insert(key.clone(), value.clone());
92        }
93        Ok(matched)
94    }
95}
96
97fn match_path(pattern: &str, path: &str) -> Option<HashMap<String, String>> {
98    let pattern_segments = crate::route::split_segments(pattern);
99    let path_segments = crate::route::split_segments(path);
100    if pattern_segments.len() != path_segments.len() {
101        return None;
102    }
103    let mut parameters = HashMap::new();
104    for (expected, actual) in pattern_segments.into_iter().zip(path_segments) {
105        if let Some(name) = crate::route::parameter_name(expected) {
106            parameters.insert(name.to_owned(), actual.to_owned());
107        } else if expected != actual {
108            return None;
109        }
110    }
111    Some(parameters)
112}