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
use response::response;
use router::Router;
use web_sys::{Request, Response, Url};
#[macro_use]
pub mod macros;
pub mod response;
pub mod router;
pub type Params = Vec<(String, String)>;
type Handler = Box<dyn Fn(Request, Params) -> Response>;
pub struct Waserv {
router: Router,
}
impl Waserv {
pub fn new() -> Waserv {
Waserv {
router: Router::new(),
}
}
pub fn handle(&self, request: Request) -> Response {
let url = Url::new(&request.url()).unwrap();
let path = format!("/{}{}", request.method().as_str(), &url.pathname());
match self.router.tree.find(&path) {
Some((func, params)) => {
let params = params
.iter()
.map(|p| (p.0.to_string(), p.1.to_string()))
.collect::<Params>();
func(request, params)
}
None => {
let body = "404 - Not Found".to_string();
let headers = headers! {
"Content-Type" => "text/html; charset=UTF-8",
"Cache-Control" => "no-cache"
};
response(body, headers, Some(404))
}
}
}
pub fn mount(&mut self, router: Router) {
self.router = router;
}
}