Skip to main content

lrwf_core/
routing.rs

1//! Routing traits: IRouter and IEndpoint.
2
3use crate::error::Result;
4use crate::http::IHttpContext;
5
6/// HTTP methods supported by the framework.
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8pub enum HttpMethod {
9    Get,
10    Post,
11    Put,
12    Delete,
13    Patch,
14    Head,
15    Options,
16}
17
18impl HttpMethod {
19    pub fn as_str(&self) -> &'static str {
20        match self {
21            HttpMethod::Get => "GET",
22            HttpMethod::Post => "POST",
23            HttpMethod::Put => "PUT",
24            HttpMethod::Delete => "DELETE",
25            HttpMethod::Patch => "PATCH",
26            HttpMethod::Head => "HEAD",
27            HttpMethod::Options => "OPTIONS",
28        }
29    }
30
31    #[allow(clippy::should_implement_trait)]
32    pub fn from_str(s: &str) -> Option<Self> {
33        match s {
34            "GET" => Some(HttpMethod::Get),
35            "POST" => Some(HttpMethod::Post),
36            "PUT" => Some(HttpMethod::Put),
37            "DELETE" => Some(HttpMethod::Delete),
38            "PATCH" => Some(HttpMethod::Patch),
39            "HEAD" => Some(HttpMethod::Head),
40            "OPTIONS" => Some(HttpMethod::Options),
41            _ => None,
42        }
43    }
44}
45
46/// Route metadata: method + path pattern.
47#[derive(Debug, Clone)]
48pub struct RouteMeta {
49    pub method: HttpMethod,
50    pub path: String,
51}
52
53impl RouteMeta {
54    pub fn new(method: HttpMethod, path: impl Into<String>) -> Self {
55        Self {
56            method,
57            path: path.into(),
58        }
59    }
60}
61
62/// An endpoint handler is the terminal component in the middleware pipeline.
63///
64/// Analogous to ASP.NET Core's RequestDelegate at the endpoint level.
65#[async_trait::async_trait]
66pub trait IEndpoint: Send + Sync {
67    async fn handle(&self, ctx: &mut dyn IHttpContext) -> Result<()>;
68}
69
70/// Router that matches incoming HTTP requests to registered endpoints.
71///
72/// Analogous to ASP.NET Core's IRouter / EndpointRouting.
73#[async_trait::async_trait]
74pub trait IRouter: Send + Sync {
75    /// Register a new route with the router.
76    fn register(&mut self, method: HttpMethod, path: &str, endpoint: Arc<dyn IEndpoint>);
77
78    /// Match an incoming request to a registered endpoint.
79    ///
80    /// Returns a tuple of:
81    /// - `Arc<dyn IEndpoint>` — the matched endpoint handler.
82    /// - `HashMap<String, String>` — route parameter values.
83    /// - `String` — the original route pattern (e.g., `"/api/users/{id}"`).
84    async fn match_route(
85        &self,
86        ctx: &mut dyn IHttpContext,
87    ) -> Result<
88        Option<(
89            Arc<dyn IEndpoint>,
90            std::collections::HashMap<String, String>,
91            String,
92        )>,
93    >;
94}
95
96use std::sync::Arc;