1use crate::HandlerFn;
4use std::collections::HashMap;
5
6#[derive(Debug, Clone, PartialEq, Eq, Hash)]
8pub enum Method {
9 Get,
10 Post,
11 Put,
12 Delete,
13}
14
15impl Method {
16 pub fn from_str(s: &str) -> Option<Self> {
18 match s.to_uppercase().as_str() {
19 "GET" => Some(Method::Get),
20 "POST" => Some(Method::Post),
21 "PUT" => Some(Method::Put),
22 "DELETE" => Some(Method::Delete),
23 _ => None,
24 }
25 }
26}
27
28impl std::fmt::Display for Method {
29 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30 match self {
31 Method::Get => write!(f, "GET"),
32 Method::Post => write!(f, "POST"),
33 Method::Put => write!(f, "PUT"),
34 Method::Delete => write!(f, "DELETE"),
35 }
36 }
37}
38
39#[derive(Debug, Clone, PartialEq, Eq, Hash)]
41struct RouteKey {
42 method: Method,
43 path: String,
44}
45
46pub struct Router {
48 routes: HashMap<RouteKey, HandlerFn>,
49}
50
51impl Router {
52 pub fn new() -> Self {
54 Self {
55 routes: HashMap::new(),
56 }
57 }
58
59 pub fn add_route(&mut self, method: Method, path: &str, handler: HandlerFn) {
61 let key = RouteKey {
62 method,
63 path: path.to_string(),
64 };
65 self.routes.insert(key, handler);
66 }
67
68 pub fn find_handler(&self, method: &Method, path: &str) -> Option<&HandlerFn> {
70 let key = RouteKey {
71 method: method.clone(),
72 path: path.to_string(),
73 };
74 self.routes.get(&key)
75 }
76}
77
78impl Default for Router {
79 fn default() -> Self {
80 Self::new()
81 }
82}