diff options
| author | omagdy7 <omar.professional8777@gmail.com> | 2024-06-05 19:10:30 +0300 |
|---|---|---|
| committer | omagdy7 <omar.professional8777@gmail.com> | 2024-06-05 19:10:30 +0300 |
| commit | 07c54da628ec776627e68c25196539389c8d965c (patch) | |
| tree | 30255789673c09d4a74e8372796f8ba4988cf4f4 /src/router.rs | |
| parent | ff75fa542a98cf9a79133a81b7716401e717bfd6 (diff) | |
| download | tiny-server-07c54da628ec776627e68c25196539389c8d965c.tar.xz tiny-server-07c54da628ec776627e68c25196539389c8d965c.zip | |
codecrafters submit [skip ci]
Diffstat (limited to 'src/router.rs')
| -rw-r--r-- | src/router.rs | 61 |
1 files changed, 40 insertions, 21 deletions
diff --git a/src/router.rs b/src/router.rs index 1d8e6f2..cbbc64a 100644 --- a/src/router.rs +++ b/src/router.rs @@ -29,34 +29,53 @@ impl Router { // 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); + match method { + Get(route) => { + let re = build_regex_from_path(&route); + let meth = Get(re.to_string()); + dbg!(&meth); + self.routes.insert(meth, handler); + } + Post(route) => { + let re = build_regex_from_path(&route); + let meth = Post(re.to_string()); + dbg!(&meth); + 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::*; - 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); + 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!(), } - Response::new("1.1".to_string(), StatusCode::NotFound, None, None).into() } } |
