aboutsummaryrefslogtreecommitdiff
path: root/src/router.rs
diff options
context:
space:
mode:
authoromagdy7 <omar.professional8777@gmail.com>2024-06-05 18:13:08 +0300
committeromagdy7 <omar.professional8777@gmail.com>2024-06-05 18:13:08 +0300
commitff75fa542a98cf9a79133a81b7716401e717bfd6 (patch)
treec9433151c9dc21a16a822d4a8f1f6f7c526b1701 /src/router.rs
parent4f9d09b58ae81e4e6144b85ce36ba424e319b779 (diff)
downloadtiny-server-ff75fa542a98cf9a79133a81b7716401e717bfd6.tar.xz
tiny-server-ff75fa542a98cf9a79133a81b7716401e717bfd6.zip
codecrafters submit [skip ci]
Diffstat (limited to 'src/router.rs')
-rw-r--r--src/router.rs62
1 files changed, 62 insertions, 0 deletions
diff --git a/src/router.rs b/src/router.rs
new file mode 100644
index 0000000..1d8e6f2
--- /dev/null
+++ b/src/router.rs
@@ -0,0 +1,62 @@
+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::*;
+
+ let method_string = match &method {
+ Get(s) | Post(s) | Put(s) => s,
+ };
+
+ let re = build_regex_from_path(method_string.as_str());
+ let meth = Get(re.to_string());
+ dbg!(&meth);
+ self.routes.insert(meth, handler);
+ self
+ }
+
+ // Handle incoming requests
+ pub fn handle(&self, request: &Request, ctx: Option<&HashMap<String, String>>) -> Response {
+ use Method::*;
+ let method_string = match &request.method {
+ Get(s) | Post(s) | Put(s) => s,
+ };
+ for (method, handler) in self.routes() {
+ let route_method = match method {
+ Get(s) | Post(s) | Put(s) => s.as_str(),
+ };
+ let re = Regex::new(route_method).unwrap();
+ dbg!(&re, method_string);
+ if re.is_match(method_string) {
+ return handler(request, ctx);
+ }
+ }
+ Response::new("1.1".to_string(), StatusCode::NotFound, None, None).into()
+ }
+}