Skip to main content

rust_webx_core/
routing.rs

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