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
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
use std::rc::Rc;
use std::string::ToString;
use std::collections::HashMap;

use task::Task;
use payload::Payload;
use route::{RouteHandler, FnHandler};
use resource::Resource;
use recognizer::{RouteRecognizer, check_pattern};
use httprequest::HttpRequest;
use httpresponse::HttpResponse;
use server::HttpHandler;


/// Middleware definition
#[allow(unused_variables)]
pub trait Middleware {

    /// Method is called when request is ready.
    fn start(&self, req: &mut HttpRequest) -> Result<(), HttpResponse> {
        Ok(())
    }

    /// Method is called when handler returns response,
    /// but before sending body streams to peer.
    fn response(&self, req: &mut HttpRequest, resp: HttpResponse) -> HttpResponse {
        resp
    }

    /// Http interation is finished
    fn finish(&self, req: &mut HttpRequest, resp: &HttpResponse) {}
}

/// Application
pub struct Application<S> {
    state: Rc<S>,
    prefix: String,
    default: Resource<S>,
    handlers: HashMap<String, Box<RouteHandler<S>>>,
    router: RouteRecognizer<Resource<S>>,
    middlewares: Rc<Vec<Box<Middleware>>>,
}

impl<S: 'static> Application<S> {

    fn run(&self, req: &mut HttpRequest, payload: Payload) -> Task {
        if let Some((params, h)) = self.router.recognize(req.path()) {
            if let Some(params) = params {
                req.set_match_info(params);
            }
            h.handle(req, payload, Rc::clone(&self.state))
        } else {
            for (prefix, handler) in &self.handlers {
                if req.path().starts_with(prefix) {
                    return handler.handle(req, payload, Rc::clone(&self.state))
                }
            }
            self.default.handle(req, payload, Rc::clone(&self.state))
        }
    }
}

impl<S: 'static> HttpHandler for Application<S> {

    fn prefix(&self) -> &str {
        &self.prefix
    }
    
    fn handle(&self, req: &mut HttpRequest, payload: Payload) -> Task {
        // run middlewares
        if !self.middlewares.is_empty() {
            for middleware in self.middlewares.iter() {
                if let Err(resp) = middleware.start(req) {
                    return Task::reply(resp)
                };
            }
            let mut task = self.run(req, payload);
            task.set_middlewares(Rc::clone(&self.middlewares));
            task
        } else {
            self.run(req, payload)
        }
    }
}

impl Application<()> {

    /// Create default `ApplicationBuilder` with no state
    pub fn default<T: ToString>(prefix: T) -> ApplicationBuilder<()> {
        ApplicationBuilder {
            parts: Some(ApplicationBuilderParts {
                state: (),
                prefix: prefix.to_string(),
                default: Resource::default(),
                handlers: HashMap::new(),
                resources: HashMap::new(),
                middlewares: Vec::new(),
            })
        }
    }
}

impl<S> Application<S> where S: 'static {

    /// Create application builder with specific state. State is shared with all
    /// routes within same application and could be
    /// accessed with `HttpContext::state()` method.
    pub fn builder<T: ToString>(prefix: T, state: S) -> ApplicationBuilder<S> {
        ApplicationBuilder {
            parts: Some(ApplicationBuilderParts {
                state: state,
                prefix: prefix.to_string(),
                default: Resource::default(),
                handlers: HashMap::new(),
                resources: HashMap::new(),
                middlewares: Vec::new(),
            })
        }
    }
}

struct ApplicationBuilderParts<S> {
    state: S,
    prefix: String,
    default: Resource<S>,
    handlers: HashMap<String, Box<RouteHandler<S>>>,
    resources: HashMap<String, Resource<S>>,
    middlewares: Vec<Box<Middleware>>,
}

/// Application builder
pub struct ApplicationBuilder<S=()> {
    parts: Option<ApplicationBuilderParts<S>>,
}

impl<S> ApplicationBuilder<S> where S: 'static {

    /// Configure resource for specific path.
    ///
    /// Resource may have variable path also. For instance, a resource with
    /// the path */a/{name}/c* would match all incoming requests with paths
    /// such as */a/b/c*, */a/1/c*, and */a/etc/c*.
    ///
    /// A variable part is specified in the form `{identifier}`, where
    /// the identifier can be used later in a request handler to access the matched
    /// value for that part. This is done by looking up the identifier
    /// in the `Params` object returned by `Request.match_info()` method.
    ///
    /// By default, each part matches the regular expression `[^{}/]+`.
    ///
    /// You can also specify a custom regex in the form `{identifier:regex}`:
    ///
    /// For instance, to route Get requests on any route matching `/users/{userid}/{friend}` and
    /// store userid and friend in the exposed Params object:
    ///
    /// ```rust
    /// extern crate actix;
    /// extern crate actix_web;
    ///
    /// use actix::*;
    /// use actix_web::*;
    ///
    /// struct MyRoute;
    ///
    /// impl Actor for MyRoute {
    ///     type Context = HttpContext<Self>;
    /// }
    ///
    /// impl Route for MyRoute {
    ///     type State = ();
    ///
    ///     fn request(req: &mut HttpRequest,
    ///                payload: Payload,
    ///                ctx: &mut HttpContext<Self>) -> RouteResult<Self> {
    ///         Reply::reply(httpcodes::HTTPOk)
    ///     }
    /// }
    /// fn main() {
    ///     let app = Application::default("/")
    ///         .resource("/test", |r| {
    ///              r.get::<MyRoute>();
    ///              r.handler(Method::HEAD, |req, payload, state| {
    ///                  httpcodes::HTTPMethodNotAllowed
    ///              });
    ///         })
    ///         .finish();
    /// }
    /// ```
    pub fn resource<F, P: ToString>(&mut self, path: P, f: F) -> &mut Self
        where F: FnOnce(&mut Resource<S>) + 'static
    {
        {
            let parts = self.parts.as_mut().expect("Use after finish");

            // add resource
            let path = path.to_string();
            if !parts.resources.contains_key(&path) {
                check_pattern(&path);
                parts.resources.insert(path.clone(), Resource::default());
            }
            f(parts.resources.get_mut(&path).unwrap());
        }
        self
    }

    /// Default resource is used if no matches route could be found.
    pub fn default_resource<F>(&mut self, f: F) -> &mut Self
        where F: FnOnce(&mut Resource<S>) + 'static
    {
        {
            let parts = self.parts.as_mut().expect("Use after finish");
            f(&mut parts.default);
        }
        self
    }

    /// This method register handler for specified path prefix.
    /// Any path that starts with this prefix matches handler.
    ///
    /// ```rust
    /// extern crate actix_web;
    /// use actix_web::*;
    ///
    /// fn main() {
    ///     let app = Application::default("/")
    ///         .handler("/test", |req, payload, state| {
    ///              match *req.method() {
    ///                  Method::GET => httpcodes::HTTPOk,
    ///                  Method::POST => httpcodes::HTTPMethodNotAllowed,
    ///                  _ => httpcodes::HTTPNotFound,
    ///              }
    ///         })
    ///         .finish();
    /// }
    /// ```
    pub fn handler<P, F, R>(&mut self, path: P, handler: F) -> &mut Self
        where F: Fn(&mut HttpRequest, Payload, &S) -> R + 'static,
              R: Into<HttpResponse> + 'static,
              P: ToString,
    {
        self.parts.as_mut().expect("Use after finish")
            .handlers.insert(path.to_string(), Box::new(FnHandler::new(handler)));
        self
    }

    /// Add path handler
    pub fn route_handler<H, P>(&mut self, path: P, h: H) -> &mut Self
        where H: RouteHandler<S> + 'static, P: ToString
    {
        {
            // add resource
            let parts = self.parts.as_mut().expect("Use after finish");
            let path = path.to_string();
            if parts.handlers.contains_key(&path) {
                panic!("Handler already registered: {:?}", path);
            }
            parts.handlers.insert(path, Box::new(h));
        }
        self
    }

    /// Construct application
    pub fn middleware<T>(&mut self, mw: T) -> &mut Self
        where T: Middleware + 'static
    {
        self.parts.as_mut().expect("Use after finish")
            .middlewares.push(Box::new(mw));
        self
    }

    /// Construct application
    pub fn finish(&mut self) -> Application<S> {
        let parts = self.parts.take().expect("Use after finish");

        let mut handlers = HashMap::new();
        let prefix = if parts.prefix.ends_with('/') {
            parts.prefix
        } else {
            parts.prefix + "/"
        };

        let mut routes = Vec::new();
        for (path, handler) in parts.resources {
            routes.push((path, handler))
        }

        for (path, mut handler) in parts.handlers {
            let path = prefix.clone() + path.trim_left_matches('/');
            handler.set_prefix(path.clone());
            handlers.insert(path, handler);
        }
        Application {
            state: Rc::new(parts.state),
            prefix: prefix.clone(),
            default: parts.default,
            handlers: handlers,
            router: RouteRecognizer::new(prefix, routes),
            middlewares: Rc::new(parts.middlewares),
        }
    }
}

impl<S: 'static> From<ApplicationBuilder<S>> for Application<S> {
    fn from(mut builder: ApplicationBuilder<S>) -> Application<S> {
        builder.finish()
    }
}

impl<S: 'static> Iterator for ApplicationBuilder<S> {
    type Item = Application<S>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.parts.is_some() {
            Some(self.finish())
        } else {
            None
        }
    }
}