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
extern crate tokio;

use std::sync::{Arc};
use regex::Regex;
use core::hash::Hasher;
use core::hash::Hash;
use std::collections::HashMap;
use tokio::io;
use tokio::net::TcpListener;
use tokio::prelude::*;

use std::net::SocketAddr;
use tokio_codec::Framed;
use std::str;

pub mod request;
pub mod response;
pub mod http;

pub use self::request::Request;
pub use self::response::Response;
pub use self::http::Http;

#[derive(Debug)]
struct MatchedRouter {
    s: String,
    regex: Regex,
    method: String,
}

impl PartialEq for MatchedRouter {
    fn eq(&self, other: &MatchedRouter) -> bool {
        self.s == other.s && self.method == other.method
    }
}
impl Eq for MatchedRouter {}

impl Hash for MatchedRouter {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.s.hash(state);
        self.method.hash(state);
    }
}

pub struct HttpError {
    status_code: u16,
    error_message: String
}

impl std::fmt::Debug for HttpError {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "HTTPError"
        )
    }
}

pub trait Handler<T: Clone> {
    fn invoke(&self, req: Request<T>) -> Result<Response, HttpError>;
}

pub struct App<T> {
    router: HashMap<MatchedRouter, Box<Handler<T> + Send + Sync>>,
    context: T
}

impl Default for App<EmptyState> {
    fn default() -> App<EmptyState> {
        App {
            router: HashMap::new(),
            context: EmptyState {}
        }
    }
}

impl<T: 'static +  Clone + Send + Sync> App<T> {
    pub fn new_with_state(context: T) -> App<T> {
        App {
            router: HashMap::new(),
            context
        }
    }

    pub fn get(self: &mut App<T>, path: &str, handler: Box<Handler<T> + Send + Sync>) {
        self.router.insert(MatchedRouter {
            method: "GET".to_string(),
            s: path.to_string(),
            regex: Regex::new(&path.to_string()).unwrap(),
        }, handler);
    }

    pub fn post(self: &mut App<T>, path: &str, handler: Box<Handler<T> + Send + Sync>) {
        self.router.insert(MatchedRouter {
            method: "POST".to_string(),
            s: path.to_string(),
            regex: Regex::new(&path.to_string()).unwrap(),
        }, handler);
    }

    pub fn inject(self: &App<T>, request: Request<T>) -> Response {
        resolve(self, request).wait().unwrap()
    }

    pub fn create_request(self: &App<T>, method: &str, path: &str, params: &str, body: Vec<u8>) -> Request<T> {
        Request {
            path: path.to_string(),
            method: method.to_string(),
            content_length: body.len(),
            content_type: None,
            header_lenght: 0,
            params: params.to_string(),
            headers: HashMap::new(),
            body,
            context: self.context.clone(),
        }
    }

    pub fn run(self: App<T>, addr: SocketAddr) -> Result<(), Box<std::error::Error>> {
        let socket = TcpListener::bind(&addr)?;
        println!("Listening on: {}", addr);

        let app = Arc::new(self);

        let done = socket
            .incoming()
            .map_err(|e| println!("failed to accept socket; error = {:?}", e))
            .for_each(move |socket| {
                let http: Http<T> = Http {
                    with_headers: false,
                    with_query_string: true,
                    context: app.context.clone()
                };
                let framed = Framed::new(socket, http);

                let (tx, rx) = framed.split();

                let app = app.clone();

                let task = tx.send_all(rx.and_then(move |request: Request<T>| {
                        resolve(&*app, request)
                    }))
                    .then(|_| future::ok(()));

                tokio::spawn(task)
            });

        tokio::run(done);

        Ok(())
    }
}

struct HandlerFor404 {}
impl<T: Clone> Handler<T> for HandlerFor404 {
    fn invoke(&self, _req: Request<T>) -> Result<Response, HttpError> {
        Ok(Response {
            status_code: 404,
            content_type: Some("text/html".to_string()),
            body: "404 Handler".to_string(),
            headers: HashMap::new()
        })
    }
}

fn resolve<T: Clone>(app: &App<T>, request: Request<T>) -> impl Future<Item=Response, Error=io::Error> + Send {
    let method = &request.method;
    let path = &request.path;
    let router = &app.router;

    let not_found: Box<Handler<T> + Send + Sync> = Box::new(HandlerFor404 {});
    let m = router.iter().find(|(matched_router, _value)| {
        matched_router.method == *method && matched_router.s == *path && matched_router.regex.is_match(path)
    });

    let func = match m {
        None => &not_found,
        Some((_m, f)) => f
    };

    future::ok::<Response, io::Error>(func.invoke(request).or_else(|e: HttpError| {
        Ok::<Response, io::Error>(Response {
            status_code: e.status_code,
            content_type: Some("text/html".to_string()),
            body: e.error_message,
            headers: HashMap::new()
        })
    }).unwrap())
}

pub fn error_500<E>(s: &'static str) -> impl Fn(E) -> HttpError {
    move |_e: E| -> HttpError {
        HttpError {
            status_code: 500,
            error_message: s.to_string()
        }
    }
}

pub fn error_400<E>(s: &'static str) -> impl Fn(E) -> HttpError {
    move |_e: E| -> HttpError {
        HttpError {
            status_code: 400,
            error_message: s.to_string()
        }
    }
}

#[derive(Clone)]
pub struct EmptyState;

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

    struct MyHandler {}
    impl<T: Clone> Handler<T> for MyHandler {
        fn invoke(&self, _req: Request<T>) -> Result<Response, HttpError> {
            Ok(Response {
                status_code: 200,
                content_type: Some("text/html".to_string()),
                body: "MyHandler".to_string(),
                headers: HashMap::new()
            })
        }
    }

    fn get_app<T: 'static>(t: T) -> App<T>
        where T: Send + Sync + Clone
    {
        let mut app = App::new_with_state(t);
        app.get("/", Box::new(MyHandler {}));
        app
    }

    #[test]
    fn dispatch_requests() {
        let app = get_app(0);

        let request = app.create_request("GET", "/", "", b"".to_vec());
        let response = app.inject(request);
        assert_eq!(response.status_code, 200);

        let request = app.create_request("GET", "/unknwon-path", "", b"".to_vec());
        let response = app.inject(request);
        assert_eq!(response.status_code, 404);
    }
}