-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrouter.rs
More file actions
52 lines (43 loc) · 1.4 KB
/
Copy pathrouter.rs
File metadata and controls
52 lines (43 loc) · 1.4 KB
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
use std::collections::HashMap;
use crate::request::{HttpRequest, Method};
use crate::response::HttpResponse;
use crate::{AppResult, Args};
pub type Handler = fn(&HttpRequest, &Args, &matchit::Params) -> AppResult<HttpResponse>;
pub enum Match<'r, 'p> {
Found(&'r Handler, matchit::Params<'r, 'p>),
MethodNotAllowed(Vec<Method>),
NotFound,
}
#[derive(Default)]
struct MethodMap {
handlers: HashMap<Method, Handler>,
}
pub struct Router {
inner: matchit::Router<MethodMap>,
}
impl Router {
pub fn new() -> Self {
Self {
inner: matchit::Router::<MethodMap>::new(),
}
}
pub fn route(mut self, method: Method, path: &str, handler: Handler) -> Self {
if let Ok(map) = self.inner.at_mut(path) {
map.value.handlers.insert(method, handler);
} else {
let mut map = MethodMap::default();
map.handlers.insert(method, handler);
let _ = self.inner.insert(path, map);
}
self
}
pub fn find<'r, 'p>(&'r self, path: &'p str, method: &Method) -> Match<'r, 'p> {
match self.inner.at(path) {
Err(_) => Match::NotFound,
Ok(map) => match map.value.handlers.get(method) {
Some(handler) => Match::Found(handler, map.params),
None => Match::MethodNotAllowed(map.value.handlers.keys().copied().collect()),
},
}
}
}