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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
extern crate iron;

use iron::prelude::*;
use iron::status;
use iron::request::Body;
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::cmp::{PartialEq, Eq};
use std::option::Option::None;

#[cfg(test)]
mod tests {

    use Router;
    use std::collections::HashMap;
    use iron::prelude::*;
    use iron::status;
    use iron::request::Body;
    use std::io::Read;

    fn test_handle(vars: HashMap<String, String>, body: &mut Body) -> IronResult<Response>
    {
        let mut string = "Vars:".to_owned();

        for (x, y) in &vars {
            string.push_str(&format!("\n{} -> {}", x, y));
        }

        string.push_str("\n");

        /* Get Body */
        let mut buf: String = "".to_owned();
        let res = body.read_to_string(&mut buf);
        string.push_str(&buf[..]);

        Ok (
            Response::with((status::Ok, string))
        )

    }

    #[test]
    fn test_router()
    {

        let mut r = Router::new();

        r.get("/id/:album", test_handle);

        let handle = move |_req: &mut Request| -> IronResult<Response> {
            return r.handle(_req);
        };

        //let server = Iron::new(handle).http("localhost:3000").unwrap();
        //println!("Server ready on 3000.");

    }
}


pub struct MatchableUrlResult {

    matches: bool,
    variables: Option<HashMap<String, String>>

}

pub struct MatchableUrl {
    url: String,
    components: Vec<(String, bool)>
}

impl Hash for MatchableUrl {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.url.hash(state);
        self.components.hash(state);
    }
}

impl PartialEq for MatchableUrl {
    fn eq(&self, other: &MatchableUrl) -> bool {
        return self.url == other.url;
    }
}

impl Eq for MatchableUrl {}

impl MatchableUrl {

    fn new(url: &str) -> MatchableUrl
    {

        let split = url[1..].split("/");
        let mut comp : Vec<(String, bool)> = Vec::new();

        for s in split {
            if s.find(":") == None {
                comp.push((s.to_owned(), true));
            } else {
                comp.push((s.to_owned(), false));
            }
        }

        return MatchableUrl { url: url.to_owned(), components: comp };

    }

    fn _match(&self, request_path: Vec<&str>) -> MatchableUrlResult
    {

        /* Check size first */
        let size = request_path.len();

        if size != self.components.len() {
            return MatchableUrlResult { matches: false, variables: None }
        }

        let mut index = 0;
        let mut vars : HashMap<String, String> = HashMap::new();

        for s in request_path {
            let (ref name, ref exac) = self.components[index];

            if *exac {
                if name != s {
                    return MatchableUrlResult { matches: false, variables: None }
                }
            } else {
                vars.insert(name[1..].to_owned(), s.to_owned());
            }

            index += 1;
        }

        return MatchableUrlResult { matches: true, variables: Some(vars) };

    }

}

pub struct Router {

    routes: HashMap<MatchableUrl, fn(HashMap<String, String>, &mut Body) -> IronResult<Response>>

}

impl Router {

    fn new() -> Router
    {
        return Router { routes: HashMap::new() };
    }

    pub fn handle(&self, _req: &mut Request) -> IronResult<Response>
    {

        for (m_url, f) in &self.routes {
            let path = _req.url.path();
            let res = m_url._match(path);
            let b = &mut _req.body;
            if res.matches {
                return f(res.variables.unwrap(), b);
            }
        }

        Ok(
            Response::with((status:: Ok, "No match."))
        )

    }

    fn get(&mut self, path: &str, f: fn(HashMap<String, String>, &mut Body) -> IronResult<Response>)
    {
        let url = MatchableUrl::new(path);
        self.routes.insert(url, f);
    }

}