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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
/*! # Rust Easy Router

 Library to add "matched" routing to the Rust web framework Iron.
 This can be used to build REST APIs with relative ease, and high stability.

 # Example Code:

 ```
 extern crate rust-easy-router;

 use rust-easy-router::*;

 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))
     )

 }

 fn main()
 {
     /* Creates new Router instance */
     let mut router = Router::new();

     /* Add routes */
     router.get("/get_image/:user/:album/:image", test_handle);

     /* Closure for Iron */
     let handle = move |_req: &mut Request| -> IronResult<Response> {
         return router.handle(_req);
     };

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

 }

 ```

 */


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 {

    /// Creates a new MatchableUrl given a "route."
    ///
    /// # Example:
    ///
    /// ```
    /// let m = MatchableUrl::new("/user/:id");
    /// ```
    pub 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 };

    }

    /// Attempts to match a request with a MatchableUrl.
    /// If this succeeds, it will also return a list of the in-url parameters.
    pub 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 {

    /// Creates a new Router.
    pub fn new() -> Router
    {
        return Router { routes: HashMap::new() };
    }

    /// The method to take in each Iron Request.
    /// Attempts to match its path with the Router's routes.
    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."))
        )

    }

    /// Function to add a new route to the Router.
    ///
    /// # Example:
    ///
    /// ```
    /// router.get("/user/:id/:album/:image");
    /// ```
    pub 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);
    }

}