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
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
extern crate http;
extern crate path_tree;

use http::Method;
use path_tree::PathTree;
use std::collections::HashMap;

pub type Trees<T> = HashMap<Method, PathTree<T>>;

#[derive(Debug)]
pub struct Router<T> {
    path: String,
    middleware: Vec<T>,
    trees: Trees<T>,
}

impl<T> Router<T>
where
    T: Clone,
{
    pub fn new() -> Self {
        Router {
            path: "/".to_owned(),
            middleware: Vec::new(),
            trees: Trees::new(),
        }
    }

    // middleware
    pub fn middleware(&mut self, handler: T) -> &mut Self {
        self.middleware.push(handler);
        self
    }

    // sub-group with prefix
    pub fn group(&mut self, path: &str, build: impl FnOnce(&mut Router<T>)) {
        let mut group = Router {
            path: join_paths(&self.path, path),
            middleware: self.middleware.clone(),
            trees: self.trees.clone(),
        };
        build(&mut group);
        self.trees = group.trees;
    }

    fn _handle(&mut self, method: Method, path: &str, handler: T) -> &mut Self {
        // TODO: combine middleware + handler to finally handler
        self.trees
            .entry(method)
            .or_insert_with(|| PathTree::new())
            .insert(path, handler);
        self
    }

    pub fn handle(&mut self, method: Method, path: &str, handler: T) -> &mut Self {
        self._handle(method, &join_paths(&self.path, path), handler)
    }

    pub fn get(&mut self, path: &str, handler: T) -> &mut Self {
        self.handle(Method::GET, path, handler)
    }

    pub fn post(&mut self, path: &str, handler: T) -> &mut Self {
        self.handle(Method::POST, path, handler)
    }

    pub fn delete(&mut self, path: &str, handler: T) -> &mut Self {
        self.handle(Method::DELETE, path, handler)
    }

    pub fn patch(&mut self, path: &str, handler: T) -> &mut Self {
        self.handle(Method::PATCH, path, handler)
    }

    pub fn put(&mut self, path: &str, handler: T) -> &mut Self {
        self.handle(Method::PUT, path, handler)
    }

    pub fn options(&mut self, path: &str, handler: T) -> &mut Self {
        self.handle(Method::OPTIONS, path, handler)
    }

    pub fn head(&mut self, path: &str, handler: T) -> &mut Self {
        self.handle(Method::HEAD, path, handler)
    }

    pub fn connect(&mut self, path: &str, handler: T) -> &mut Self {
        self.handle(Method::CONNECT, path, handler)
    }

    pub fn trace(&mut self, path: &str, handler: T) -> &mut Self {
        self.handle(Method::TRACE, path, handler)
    }

    pub fn any(&mut self, path: &str, handler: T) -> &mut Self {
        let path = &join_paths(&self.path, path);
        self._handle(Method::GET, path, handler.clone());
        self._handle(Method::POST, path, handler.clone());
        self._handle(Method::DELETE, path, handler.clone());
        self._handle(Method::PATCH, path, handler.clone());
        self._handle(Method::PUT, path, handler.clone());
        self._handle(Method::OPTIONS, path, handler.clone());
        self._handle(Method::HEAD, path, handler.clone());
        self._handle(Method::CONNECT, path, handler.clone());
        self._handle(Method::TRACE, path, handler.clone())
    }

    pub fn find<'a>(
        &'a self,
        method: &'a Method,
        path: &'a str,
    ) -> Option<(&'a T, Vec<(&'a str, &'a str)>)> {
        let tree = self.trees.get(method)?;
        tree.find(path)
    }
}

fn join_paths(a: &str, mut b: &str) -> String {
    if b.is_empty() {
        return a.to_owned();
    }
    b = b.trim_start_matches('/');
    a.trim_end_matches('/').to_owned() + "/" + b
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn new_router() {
        type F = fn() -> usize;
        let mut router = Router::<F>::new();

        // Simple group: v1
        router.group("/v1", |v1| {
            v1.get("/login", || 0);
            v1.post("/submit", || 1);
            v1.delete("/read", || 2);
        });

        // Simple group: v2
        router.group("/v2", |v2| {
            v2.get("/login", || 0);
            v2.post("/submit", || 1);
            v2.delete("/read", || 2);
        });

        router.get("/foo", || 3);
        router.post("/bar", || 4);
        router.delete("/baz", || 5);

        dbg!(&router);
    }
}