Skip to main content

yaiko_core/
router.rs

1use crate::static_files::StaticFiles;
2use crate::{Handler, Middleware, Request, Response};
3use async_trait::async_trait;
4use hyper::Method;
5use regex::Regex;
6use std::collections::HashMap;
7use std::fmt;
8use std::sync::Arc;
9
10#[derive(Clone)]
11pub struct Route {
12    pub path: String,
13    pub method: Method,
14    pub regex: Regex,
15    pub param_names: Vec<String>,
16    pub handler: Arc<dyn Handler>,
17    pub strip_prefix: Option<String>,
18}
19
20// Implement Debug manually for Route
21impl fmt::Debug for Route {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        f.debug_struct("Route")
24            .field("path", &self.path)
25            .field("method", &self.method)
26            .field("param_names", &self.param_names)
27            .field("strip_prefix", &self.strip_prefix)
28            .finish()
29    }
30}
31impl Route {
32    pub fn new(method: Method, path: &str, handler: Arc<dyn Handler>) -> Self {
33        let mut normalized_path = path.trim_end_matches('/');
34        if normalized_path.is_empty() {
35            normalized_path = "/";
36        }
37        let (regex, param_names) = Self::path_to_regex(normalized_path);
38        Route {
39            path: normalized_path.to_string(),
40            method,
41            regex,
42            param_names,
43            handler,
44            strip_prefix: None,
45        }
46    }
47
48    fn mounted(method: Method, path: &str, handler: Arc<dyn Handler>, prefix: &str) -> Self {
49        let mut route = Self::new(method, path, handler);
50        route.strip_prefix = Some(prefix.to_string());
51        route
52    }
53
54    fn path_to_regex(path: &str) -> (Regex, Vec<String>) {
55        let mut regex_str = String::new();
56        let mut param_names = Vec::new();
57        let mut chars = path.chars().peekable();
58
59        regex_str.push('^');
60
61        while let Some(ch) = chars.next() {
62            match ch {
63                ':' => {
64                    let mut param_name = String::new();
65                    while let Some(&next_ch) = chars.peek() {
66                        if next_ch.is_alphanumeric() || next_ch == '_' {
67                            param_name.push(chars.next().unwrap());
68                        } else {
69                            break;
70                        }
71                    }
72                    param_names.push(param_name);
73                    regex_str.push_str("([^/]+)");
74                }
75                '*' => {
76                    regex_str.push_str("(.*)");
77                }
78                '.' | '+' | '?' | '^' | '$' | '{' | '}' | '[' | ']' | '|' | '(' | ')' | '\\' => {
79                    regex_str.push('\\');
80                    regex_str.push(ch);
81                }
82                _ => regex_str.push(ch),
83            }
84        }
85
86        regex_str.push('$');
87        (Regex::new(&regex_str).unwrap(), param_names)
88    }
89
90    pub fn matches_path(&self, path: &str) -> Option<HashMap<String, String>> {
91        if let Some(captures) = self.regex.captures(path) {
92            let mut params = HashMap::new();
93            for (i, param_name) in self.param_names.iter().enumerate() {
94                if let Some(capture) = captures.get(i + 1) {
95                    params.insert(param_name.clone(), capture.as_str().to_string());
96                }
97            }
98            Some(params)
99        } else {
100            None
101        }
102    }
103}
104
105#[derive(Clone)]
106pub struct Router {
107    routes: Vec<Route>,
108    middleware: Vec<Arc<dyn Middleware>>,
109    pub static_handler: Option<Arc<StaticFiles>>,
110    pub static_prefix: Option<String>,
111}
112
113impl Default for Router {
114    fn default() -> Self {
115        Self::new()
116    }
117}
118
119impl Router {
120    pub fn new() -> Self {
121        Router {
122            routes: Vec::new(),
123            middleware: Vec::new(),
124            static_handler: None,
125            static_prefix: None,
126        }
127    }
128
129    pub fn get<H>(mut self, path: &str, handler: H) -> Self
130    where
131        H: Handler + 'static,
132    {
133        self.routes
134            .push(Route::new(Method::GET, path, Arc::new(handler)));
135        self
136    }
137
138    pub fn post<H>(mut self, path: &str, handler: H) -> Self
139    where
140        H: Handler + 'static,
141    {
142        self.routes
143            .push(Route::new(Method::POST, path, Arc::new(handler)));
144        self
145    }
146
147    pub fn put<H>(mut self, path: &str, handler: H) -> Self
148    where
149        H: Handler + 'static,
150    {
151        self.routes
152            .push(Route::new(Method::PUT, path, Arc::new(handler)));
153        self
154    }
155
156    pub fn delete<H>(mut self, path: &str, handler: H) -> Self
157    where
158        H: Handler + 'static,
159    {
160        self.routes
161            .push(Route::new(Method::DELETE, path, Arc::new(handler)));
162        self
163    }
164
165    pub fn patch<H>(mut self, path: &str, handler: H) -> Self
166    where
167        H: Handler + 'static,
168    {
169        self.routes
170            .push(Route::new(Method::PATCH, path, Arc::new(handler)));
171        self
172    }
173
174    pub fn options<H>(mut self, path: &str, handler: H) -> Self
175    where
176        H: Handler + 'static,
177    {
178        self.routes
179            .push(Route::new(Method::OPTIONS, path, Arc::new(handler)));
180        self
181    }
182
183    pub fn head<H>(mut self, path: &str, handler: H) -> Self
184    where
185        H: Handler + 'static,
186    {
187        self.routes
188            .push(Route::new(Method::HEAD, path, Arc::new(handler)));
189        self
190    }
191
192    /// Mount static files from a directory at a URL prefix
193    ///
194    /// # Example
195    /// ```rust
196    /// use yaiko_core::Router;
197    ///
198    /// let router = Router::new()
199    ///     .static_files("/static", "./public");
200    /// # let _ = router;
201    /// ```
202    pub fn static_files(mut self, prefix: &str, dir: &str) -> Self {
203        self.static_handler = Some(Arc::new(StaticFiles::new(dir, prefix)));
204        self.static_prefix = Some(prefix.to_string());
205        self
206    }
207
208    pub fn use_middleware<M>(mut self, middleware: M) -> Self
209    where
210        M: Middleware + 'static,
211    {
212        self.middleware.push(Arc::new(middleware));
213        self
214    }
215
216    /// Mount a sub-router at a given path prefix
217    pub fn mount(mut self, path: &str, router: Router) -> Self {
218        // We create a route that matches the prefix and anything after it
219        let mut prefix = path.trim_end_matches('/').to_string();
220        if prefix.is_empty() {
221            prefix = "/".to_string();
222        }
223
224        let path_pattern = format!("{}/*", prefix);
225        // We mount it for all common methods
226        for method in [
227            Method::GET,
228            Method::POST,
229            Method::PUT,
230            Method::DELETE,
231            Method::PATCH,
232            Method::OPTIONS,
233            Method::HEAD,
234        ] {
235            let handler = Arc::new(router.clone());
236            self.routes.push(Route::mounted(
237                method.clone(),
238                &prefix,
239                handler.clone(),
240                &prefix,
241            ));
242            self.routes
243                .push(Route::mounted(method, &path_pattern, handler, &prefix));
244        }
245        self
246    }
247
248    pub async fn handle_request(
249        &self,
250        mut req: Request,
251    ) -> Result<Response, Box<dyn std::error::Error + Send + Sync>> {
252        let mut original_path = req.uri.path().trim_end_matches('/').to_string();
253        if original_path.is_empty() {
254            original_path = "/".to_string();
255        }
256        let target_method = req.method.clone();
257
258        // Track allowed methods for 405 Method Not Allowed / OPTIONS fallbacks
259        let mut allowed_methods = Vec::new();
260        let mut found_match = false;
261
262        // Find matching route
263        for route in &self.routes {
264            if let Some(params) = route.matches_path(&original_path) {
265                found_match = true;
266                allowed_methods.push(route.method.as_str().to_string());
267
268                // Allow exact method match OR auto-resolve HEAD requests to GET routes
269                if route.method == target_method
270                    || (target_method == Method::HEAD && route.method == Method::GET)
271                {
272                    req.params = params;
273
274                    // If it's a mount route (ends with /*), we need to strip the prefix for the sub-router
275                    if let Some(prefix) = &route.strip_prefix {
276                        let mut new_path = original_path
277                            .strip_prefix(prefix)
278                            .unwrap_or(&original_path)
279                            .to_string();
280                        if new_path.is_empty() {
281                            new_path = "/".to_string();
282                        }
283
284                        // Replace the URI path but keep query params
285                        let mut parts = req.uri.clone().into_parts();
286                        let path_and_query = match parts.path_and_query {
287                            Some(pq) => {
288                                if let Some(query) = pq.query() {
289                                    hyper::http::uri::PathAndQuery::try_from(
290                                        format!("{}?{}", new_path, query).as_str(),
291                                    )
292                                    .ok()
293                                } else {
294                                    hyper::http::uri::PathAndQuery::try_from(new_path.as_str()).ok()
295                                }
296                            }
297                            None => {
298                                hyper::http::uri::PathAndQuery::try_from(new_path.as_str()).ok()
299                            }
300                        };
301                        parts.path_and_query = path_and_query;
302                        if let Ok(new_uri) = hyper::Uri::from_parts(parts) {
303                            req.uri = new_uri;
304                        }
305                    }
306
307                    // Apply middleware chain
308                    let handler = route.handler.clone();
309                    let final_handler =
310                        self.middleware
311                            .iter()
312                            .rev()
313                            .fold(handler, |next, middleware| {
314                                let middleware = middleware.clone();
315                                Arc::new(MiddlewareHandler { middleware, next })
316                            });
317
318                    return final_handler.handle(req).await;
319                }
320            }
321        }
322
323        // Return a global OPTIONS preflight success safely if ANY route path matched returning the Allow/CORS options
324        if found_match && target_method == Method::OPTIONS {
325            allowed_methods.sort();
326            allowed_methods.dedup();
327            let allow_header = allowed_methods.join(", ");
328            return Ok(Response::new()
329                .status(hyper::StatusCode::OK)
330                .header("Allow", &allow_header)
331                .header("Access-Control-Allow-Methods", &allow_header));
332        }
333
334        // Return a 405 Method Not Allowed error returning the Allow list safely preventing false 404 logic
335        if found_match {
336            allowed_methods.sort();
337            allowed_methods.dedup();
338            return Ok(Response::new()
339                .status(hyper::StatusCode::METHOD_NOT_ALLOWED)
340                .header("Allow", &allowed_methods.join(", "))
341                .text("Method Not Allowed"));
342        }
343
344        // Try static files if configured
345        if let (Some(ref handler), Some(ref prefix)) = (&self.static_handler, &self.static_prefix) {
346            let path = req.uri.path();
347            if path.starts_with(prefix) {
348                return handler.handle(req).await;
349            }
350        }
351
352        // No route found
353        Ok(Response::new()
354            .status(hyper::StatusCode::NOT_FOUND)
355            .text("Not Found"))
356    }
357}
358
359// Helper struct to chain middleware
360struct MiddlewareHandler {
361    middleware: Arc<dyn Middleware>,
362    next: Arc<dyn Handler>,
363}
364
365#[async_trait]
366impl Handler for MiddlewareHandler {
367    async fn handle(
368        &self,
369        req: Request,
370    ) -> Result<Response, Box<dyn std::error::Error + Send + Sync>> {
371        self.middleware.handle(req, self.next.clone()).await
372    }
373}
374
375#[async_trait]
376impl Handler for Router {
377    async fn handle(
378        &self,
379        req: Request,
380    ) -> Result<Response, Box<dyn std::error::Error + Send + Sync>> {
381        self.handle_request(req).await
382    }
383}
384
385#[cfg(test)]
386mod tests {
387    use super::*;
388    use hyper::Body;
389
390    #[tokio::test]
391    async fn mounted_router_matches_mount_root() {
392        let subrouter = Router::new().get("/", |_req: Request| async {
393            Ok(Response::new().text("subrouter root"))
394        });
395        let router = Router::new().mount("/api", subrouter);
396        let req = Request::from_hyper(
397            hyper::Request::builder()
398                .method("GET")
399                .uri("/api")
400                .body(Body::empty())
401                .unwrap(),
402        )
403        .await
404        .unwrap();
405
406        let response = router.handle_request(req).await.unwrap();
407        let body = hyper::body::to_bytes(response.body).await.unwrap();
408
409        assert_eq!(response.status, hyper::StatusCode::OK);
410        assert_eq!(&body[..], b"subrouter root");
411    }
412}