rocal_core/
route_handler.rs1use std::cell::RefCell;
2use std::rc::Rc;
3
4use url::Url;
5use web_sys::window;
6
7use crate::enums::request_method::RequestMethod;
8use crate::router::Router;
9
10pub struct RouteHandler {
11 router: Rc<RefCell<Router>>,
12 not_found: Box<dyn Fn()>,
13}
14
15impl RouteHandler {
16 pub fn new(router: Rc<RefCell<Router>>, not_found: Option<Box<dyn Fn()>>) -> Self {
17 let not_found = match not_found {
18 Some(nf) => nf,
19 None => Box::new(Self::default_not_found_page),
20 };
21
22 RouteHandler { router, not_found }
23 }
24
25 pub async fn handle_route(&self) {
26 let href = if let Some(w) = window() {
27 if let Ok(href) = w.location().href() {
28 href
29 } else {
30 (self.not_found)();
31 return;
32 }
33 } else {
34 (self.not_found)();
35 return;
36 };
37
38 let url = match Url::parse(&href) {
39 Ok(u) => u,
40 Err(_) => {
41 (self.not_found)();
42 return;
43 }
44 };
45
46 let path = url.fragment().unwrap_or_else(|| "/");
47
48 if !self
49 .router
50 .borrow()
51 .resolve(RequestMethod::Get, path, None)
52 .await
53 {
54 (self.not_found)();
55 }
56 }
57
58 fn default_not_found_page() {
59 web_sys::window()
60 .unwrap()
61 .document()
62 .unwrap()
63 .body()
64 .unwrap()
65 .set_inner_html("<h1>404 - Page Not Found</h1>");
66 }
67}