aboutsummaryrefslogtreecommitdiff
path: root/src/router.rs
blob: 7b1313b47b224c42a57fd77247b75f4a79e512e1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
use crate::{
    extractor::build_regex_from_path,
    http_types::{Method, StatusCode},
    request::Request,
    response::Response,
};
use regex::Regex;
use std::collections::HashMap;

type Handler = fn(&Request, Option<&HashMap<String, String>>) -> Response;
type Routes = HashMap<Method, Handler>;

pub struct Router {
    routes: Routes,
}

impl Router {
    // Create a new Router
    pub fn new() -> Self {
        Router {
            routes: HashMap::new(),
        }
    }

    pub fn routes(&self) -> &Routes {
        &self.routes
    }

    // Add a route to the router
    pub fn route(&mut self, method: Method, handler: Handler) -> &mut Self {
        use Method::*;
        match method {
            Get(route) => {
                let re = build_regex_from_path(&route);
                let meth = Get(re.to_string());
                self.routes.insert(meth, handler);
            }
            Post(route) => {
                let re = build_regex_from_path(&route);
                let meth = Post(re.to_string());
                self.routes.insert(meth, handler);
            }
            Put(_) => todo!(),
        }
        self
    }

    // Handle incoming requests
    pub fn handle(&self, request: &Request, ctx: Option<&HashMap<String, String>>) -> Response {
        use Method::*;
        match &request.method {
            Get(request_method) => {
                for (method, handler) in self.routes() {
                    if let Get(method_string) = method {
                        let re = Regex::new(method_string).unwrap();
                        // dbg!(&re, request_method);
                        if re.is_match(request_method) {
                            return handler(request, ctx);
                        }
                    }
                }
                Response::new("1.1".to_string(), StatusCode::NotFound, None, None).into()
            }
            Post(request_method) => {
                for (method, handler) in self.routes() {
                    if let Post(method_string) = method {
                        let re = Regex::new(method_string).unwrap();
                        // dbg!(&re, request_method);
                        if re.is_match(request_method) {
                            return handler(request, ctx);
                        }
                    }
                }
                Response::new("1.1".to_string(), StatusCode::NotFound, None, None).into()
            }
            Put(_) => todo!(),
        }
    }
}