rust_webx_core/
routing.rs1use crate::error::Result;
4use crate::http::IHttpContext;
5use std::sync::Arc;
6
7#[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#[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#[async_trait::async_trait]
67pub trait IEndpoint: Send + Sync {
68 async fn handle(&self, ctx: &mut dyn IHttpContext) -> Result<()>;
69}
70
71#[async_trait::async_trait]
75pub trait IRouter: Send + Sync {
76 fn register(&mut self, method: HttpMethod, path: &str, endpoint: Arc<dyn IEndpoint>);
78
79 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}