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
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
use std::mem;
use std::rc::Rc;
use std::cell::UnsafeCell;
use std::collections::HashMap;

use http::Method;
use handler::Reply;
use router::{Router, Resource};
use resource::{ResourceHandler};
use header::ContentEncoding;
use handler::{Handler, RouteHandler, WrapHandler, FromRequest, Responder};
use httprequest::HttpRequest;
use pipeline::{Pipeline, PipelineHandler, HandlerType};
use middleware::Middleware;
use server::{HttpHandler, IntoHttpHandler, HttpHandlerTask, ServerSettings};

#[deprecated(since="0.5.0", note="please use `actix_web::App` instead")]
pub type Application<S> = App<S>;

/// Application
pub struct HttpApplication<S=()> {
    state: Rc<S>,
    prefix: String,
    prefix_len: usize,
    router: Router,
    inner: Rc<UnsafeCell<Inner<S>>>,
    middlewares: Rc<Vec<Box<Middleware<S>>>>,
}

pub(crate) struct Inner<S> {
    prefix: usize,
    default: ResourceHandler<S>,
    encoding: ContentEncoding,
    resources: Vec<ResourceHandler<S>>,
    handlers: Vec<(String, Box<RouteHandler<S>>)>,
}

impl<S: 'static> PipelineHandler<S> for Inner<S> {

    fn encoding(&self) -> ContentEncoding {
        self.encoding
    }

    fn handle(&mut self, req: HttpRequest<S>, htype: HandlerType) -> Reply {
        match htype {
            HandlerType::Normal(idx) =>
                self.resources[idx].handle(req, Some(&mut self.default)),
            HandlerType::Handler(idx) =>
                self.handlers[idx].1.handle(req),
            HandlerType::Default =>
                self.default.handle(req, None)
        }
    }
}

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

    #[inline]
    fn as_ref(&self) -> &Inner<S> {
        unsafe{&*self.inner.get()}
    }

    #[inline]
    fn get_handler(&self, req: &mut HttpRequest<S>) -> HandlerType {
        if let Some(idx) = self.router.recognize(req) {
            HandlerType::Normal(idx)
        } else {
            let inner = self.as_ref();
            for idx in 0..inner.handlers.len() {
                let &(ref prefix, _) = &inner.handlers[idx];
                let m = {
                    let path = &req.path()[inner.prefix..];
                    path.starts_with(prefix) && (
                        path.len() == prefix.len() ||
                            path.split_at(prefix.len()).1.starts_with('/'))
                };

                if m {
                    let path: &'static str = unsafe {
                        mem::transmute(&req.path()[inner.prefix+prefix.len()..]) };
                    if path.is_empty() {
                        req.match_info_mut().add("tail", "");
                    } else {
                        req.match_info_mut().add("tail", path.split_at(1).1);
                    }
                    return HandlerType::Handler(idx)
                }
            }
            HandlerType::Default
        }
    }

    #[cfg(test)]
    pub(crate) fn run(&mut self, mut req: HttpRequest<S>) -> Reply {
        let tp = self.get_handler(&mut req);
        unsafe{&mut *self.inner.get()}.handle(req, tp)
    }

    #[cfg(test)]
    pub(crate) fn prepare_request(&self, req: HttpRequest) -> HttpRequest<S> {
        req.with_state(Rc::clone(&self.state), self.router.clone())
    }
}

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

    fn handle(&mut self, req: HttpRequest) -> Result<Box<HttpHandlerTask>, HttpRequest> {
        let m = {
            let path = req.path();
            path.starts_with(&self.prefix) && (
                path.len() == self.prefix_len ||
                    path.split_at(self.prefix_len).1.starts_with('/'))
        };
        if m {
            let mut req = req.with_state(Rc::clone(&self.state), self.router.clone());
            let tp = self.get_handler(&mut req);
            let inner = Rc::clone(&self.inner);
            Ok(Box::new(Pipeline::new(req, Rc::clone(&self.middlewares), inner, tp)))
        } else {
            Err(req)
        }
    }
}

struct ApplicationParts<S> {
    state: S,
    prefix: String,
    settings: ServerSettings,
    default: ResourceHandler<S>,
    resources: Vec<(Resource, Option<ResourceHandler<S>>)>,
    handlers: Vec<(String, Box<RouteHandler<S>>)>,
    external: HashMap<String, Resource>,
    encoding: ContentEncoding,
    middlewares: Vec<Box<Middleware<S>>>,
}

/// Structure that follows the builder pattern for building application instances.
pub struct App<S=()> {
    parts: Option<ApplicationParts<S>>,
}

impl App<()> {

   /// Create application with empty state. Application can
    /// be configured with a builder-like pattern.
    pub fn new() -> App<()> {
        App {
            parts: Some(ApplicationParts {
                state: (),
                prefix: "/".to_owned(),
                settings: ServerSettings::default(),
                default: ResourceHandler::default_not_found(),
                resources: Vec::new(),
                handlers: Vec::new(),
                external: HashMap::new(),
                encoding: ContentEncoding::Auto,
                middlewares: Vec::new(),
            })
        }
    }
}

impl Default for App<()> {
    fn default() -> Self {
        App::new()
    }
}

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

    /// Create application with specified state. Application can be
    /// configured with a builder-like pattern.
    ///
    /// State is shared with all resources within same application and
    /// could be accessed with `HttpRequest::state()` method.
    pub fn with_state(state: S) -> App<S> {
        App {
            parts: Some(ApplicationParts {
                state,
                prefix: "/".to_owned(),
                settings: ServerSettings::default(),
                default: ResourceHandler::default_not_found(),
                resources: Vec::new(),
                handlers: Vec::new(),
                external: HashMap::new(),
                middlewares: Vec::new(),
                encoding: ContentEncoding::Auto,
            })
        }
    }

    /// Set application prefix.
    ///
    /// Only requests that match the application's prefix get
    /// processed by this application.
    ///
    /// The application prefix always contains a leading slash (`/`).
    /// If the supplied prefix does not contain leading slash, it is
    /// inserted.
    ///
    /// Prefix should consist of valid path segments. i.e for an
    /// application with the prefix `/app` any request with the paths
    /// `/app`, `/app/` or `/app/test` would match, but the path
    /// `/application` would not.
    ///
    /// In the following example only requests with an `/app/` path
    /// prefix get handled. Requests with path `/app/test/` would be
    /// handled, while requests with the paths `/application` or
    /// `/other/...` would return `NOT FOUND`.
    ///
    /// ```rust
    /// # extern crate actix_web;
    /// use actix_web::{http, App, HttpResponse};
    ///
    /// fn main() {
    ///     let app = App::new()
    ///         .prefix("/app")
    ///         .resource("/test", |r| {
    ///              r.get().f(|_| HttpResponse::Ok());
    ///              r.head().f(|_| HttpResponse::MethodNotAllowed());
    ///         })
    ///         .finish();
    /// }
    /// ```
    pub fn prefix<P: Into<String>>(mut self, prefix: P) -> App<S> {
        {
            let parts = self.parts.as_mut().expect("Use after finish");
            let mut prefix = prefix.into();
            if !prefix.starts_with('/') {
                prefix.insert(0, '/')
            }
            parts.prefix = prefix;
        }
        self
    }

    /// Configure route for a specific path.
    ///
    /// This is a simplified version of the `App::resource()` method.
    /// Handler functions need to accept one request extractor
    /// argument.
    ///
    /// This method could be called multiple times, in that case
    /// multiple routes would be registered for same resource path.
    ///
    /// ```rust
    /// # extern crate actix_web;
    /// use actix_web::{http, App, HttpRequest, HttpResponse};
    ///
    /// fn main() {
    ///     let app = App::new()
    ///         .route("/test", http::Method::GET,
    ///                |_: HttpRequest| HttpResponse::Ok())
    ///         .route("/test", http::Method::POST,
    ///                |_: HttpRequest| HttpResponse::MethodNotAllowed());
    /// }
    /// ```
    pub fn route<T, F, R>(mut self, path: &str, method: Method, f: F) -> App<S>
        where F: Fn(T) -> R + 'static,
              R: Responder + 'static,
              T: FromRequest<S> + 'static,
    {
        {
            let parts: &mut ApplicationParts<S> = unsafe{
                mem::transmute(self.parts.as_mut().expect("Use after finish"))};

            // get resource handler
            for &mut (ref pattern, ref mut handler) in &mut parts.resources {
                if let Some(ref mut handler) = *handler {
                    if pattern.pattern() == path {
                        handler.method(method).with(f);
                        return self
                    }
                }
            }

            let mut handler = ResourceHandler::default();
            handler.method(method).with(f);
            let pattern = Resource::new(handler.get_name(), path);
            parts.resources.push((pattern, Some(handler)));
        }
        self
    }

    /// Configure resource for a specific path.
    ///
    /// Resources may have variable path segments. For example, a
    /// resource with the path `/a/{name}/c` would match all incoming
    /// requests with paths such as `/a/b/c`, `/a/1/c`, or `/a/etc/c`.
    ///
    /// A variable segment is specified in the form `{identifier}`,
    /// where the identifier can be used later in a request handler to
    /// access the matched value for that segment. This is done by
    /// looking up the identifier in the `Params` object returned by
    /// `HttpRequest.match_info()` method.
    ///
    /// By default, each segment 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_web;
    /// use actix_web::{http, App, HttpResponse};
    ///
    /// fn main() {
    ///     let app = App::new()
    ///         .resource("/test", |r| {
    ///              r.get().f(|_| HttpResponse::Ok());
    ///              r.head().f(|_| HttpResponse::MethodNotAllowed());
    ///         });
    /// }
    /// ```
    pub fn resource<F, R>(mut self, path: &str, f: F) -> App<S>
        where F: FnOnce(&mut ResourceHandler<S>) -> R + 'static
    {
        {
            let parts = self.parts.as_mut().expect("Use after finish");

            // add resource handler
            let mut handler = ResourceHandler::default();
            f(&mut handler);

            let pattern = Resource::new(handler.get_name(), path);
            parts.resources.push((pattern, Some(handler)));
        }
        self
    }

    /// Configure resource for a specific path.
    #[doc(hidden)]
    pub fn register_resource(&mut self, path: &str, resource: ResourceHandler<S>) {
        let pattern = Resource::new(resource.get_name(), path);
        self.parts.as_mut().expect("Use after finish")
            .resources.push((pattern, Some(resource)));
    }

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

    /// Set default content encoding. `ContentEncoding::Auto` is set by default.
    pub fn default_encoding<F>(mut self, encoding: ContentEncoding) -> App<S>
    {
        {
            let parts = self.parts.as_mut().expect("Use after finish");
            parts.encoding = encoding;
        }
        self
    }

    /// Register an external resource.
    ///
    /// External resources are useful for URL generation purposes only
    /// and are never considered for matching at request time. Calls to
    /// `HttpRequest::url_for()` will work as expected.
    ///
    /// ```rust
    /// # extern crate actix_web;
    /// use actix_web::{App, HttpRequest, HttpResponse, Result};
    ///
    /// fn index(mut req: HttpRequest) -> Result<HttpResponse> {
    ///    let url = req.url_for("youtube", &["oHg5SJYRHA0"])?;
    ///    assert_eq!(url.as_str(), "https://youtube.com/watch/oHg5SJYRHA0");
    ///    Ok(HttpResponse::Ok().into())
    /// }
    ///
    /// fn main() {
    ///     let app = App::new()
    ///         .resource("/index.html", |r| r.get().f(index))
    ///         .external_resource("youtube", "https://youtube.com/watch/{video_id}")
    ///         .finish();
    /// }
    /// ```
    pub fn external_resource<T, U>(mut self, name: T, url: U) -> App<S>
        where T: AsRef<str>, U: AsRef<str>
    {
        {
            let parts = self.parts.as_mut().expect("Use after finish");

            if parts.external.contains_key(name.as_ref()) {
                panic!("External resource {:?} is registered.", name.as_ref());
            }
            parts.external.insert(
                String::from(name.as_ref()),
                Resource::external(name.as_ref(), url.as_ref()));
        }
        self
    }

    /// Configure handler for specific path prefix.
    ///
    /// A path prefix consists of valid path segments, i.e for the
    /// prefix `/app` any request with the paths `/app`, `/app/` or
    /// `/app/test` would match, but the path `/application` would
    /// not.
    ///
    /// ```rust
    /// # extern crate actix_web;
    /// use actix_web::{http, App, HttpRequest, HttpResponse};
    ///
    /// fn main() {
    ///     let app = App::new()
    ///         .handler("/app", |req: HttpRequest| {
    ///             match *req.method() {
    ///                 http::Method::GET => HttpResponse::Ok(),
    ///                 http::Method::POST => HttpResponse::MethodNotAllowed(),
    ///                 _ => HttpResponse::NotFound(),
    ///         }});
    /// }
    /// ```
    pub fn handler<H: Handler<S>>(mut self, path: &str, handler: H) -> App<S>
    {
        {
            let mut path = path.trim().trim_right_matches('/').to_owned();
            if !path.is_empty() && !path.starts_with('/') {
                path.insert(0, '/')
            }
            let parts = self.parts.as_mut().expect("Use after finish");

            parts.handlers.push((path, Box::new(WrapHandler::new(handler))));
        }
        self
    }

    /// Register a middleware.
    pub fn middleware<M: Middleware<S>>(mut self, mw: M) -> App<S> {
        self.parts.as_mut().expect("Use after finish")
            .middlewares.push(Box::new(mw));
        self
    }

    /// Run external configuration as part of the application building
    /// process
    ///
    /// This function is useful for moving parts of configuration to a
    /// different module or event library. For example we can move
    /// some of the resources' configuration to different module.
    ///
    /// ```rust
    /// # extern crate actix_web;
    /// use actix_web::{App, HttpResponse, fs, middleware};
    ///
    /// // this function could be located in different module
    /// fn config(app: App) -> App {
    ///     app
    ///         .resource("/test", |r| {
    ///              r.get().f(|_| HttpResponse::Ok());
    ///              r.head().f(|_| HttpResponse::MethodNotAllowed());
    ///         })
    /// }
    ///
    /// fn main() {
    ///     let app = App::new()
    ///         .middleware(middleware::Logger::default())
    ///         .configure(config)  // <- register resources
    ///         .handler("/static", fs::StaticFiles::new("."));
    /// }
    /// ```
    pub fn configure<F>(self, cfg: F) -> App<S>
        where F: Fn(App<S>) -> App<S>
    {
        cfg(self)
    }

    /// Finish application configuration and create `HttpHandler` object.
    pub fn finish(&mut self) -> HttpApplication<S> {
        let parts = self.parts.take().expect("Use after finish");
        let prefix = parts.prefix.trim().trim_right_matches('/');
        let (prefix, prefix_len) = if prefix.is_empty() {
            ("/".to_owned(), 0)
        } else {
            (prefix.to_owned(), prefix.len())
        };

        let mut resources = parts.resources;
        for (_, pattern) in parts.external {
            resources.push((pattern, None));
        }

        let (router, resources) = Router::new(&prefix, parts.settings, resources);

        let inner = Rc::new(UnsafeCell::new(
            Inner {
                prefix: prefix_len,
                default: parts.default,
                encoding: parts.encoding,
                handlers: parts.handlers,
                resources,
            }
        ));

        HttpApplication {
            state: Rc::new(parts.state),
            router: router.clone(),
            middlewares: Rc::new(parts.middlewares),
            prefix,
            prefix_len,
            inner,
        }
    }

    /// Convenience method for creating `Box<HttpHandler>` instances.
    ///
    /// This method is useful if you need to register multiple
    /// application instances with different state.
    ///
    /// ```rust
    /// # use std::thread;
    /// # extern crate actix_web;
    /// use actix_web::{server, App, HttpResponse};
    ///
    /// struct State1;
    ///
    /// struct State2;
    ///
    /// fn main() {
    /// # thread::spawn(|| {
    ///     server::new(|| { vec![
    ///         App::with_state(State1)
    ///              .prefix("/app1")
    ///              .resource("/", |r| r.f(|r| HttpResponse::Ok()))
    ///              .boxed(),
    ///         App::with_state(State2)
    ///              .prefix("/app2")
    ///              .resource("/", |r| r.f(|r| HttpResponse::Ok()))
    ///              .boxed() ]})
    ///         .bind("127.0.0.1:8080").unwrap()
    ///         .run()
    /// # });
    /// }
    /// ```
    pub fn boxed(mut self) -> Box<HttpHandler> {
        Box::new(self.finish())
    }
}

impl<S: 'static> IntoHttpHandler for App<S> {
    type Handler = HttpApplication<S>;

    fn into_handler(mut self, settings: ServerSettings) -> HttpApplication<S> {
        {
            let parts = self.parts.as_mut().expect("Use after finish");
            parts.settings = settings;
        }
        self.finish()
    }
}

impl<'a, S: 'static> IntoHttpHandler for &'a mut App<S> {
    type Handler = HttpApplication<S>;

    fn into_handler(self, settings: ServerSettings) -> HttpApplication<S> {
        {
            let parts = self.parts.as_mut().expect("Use after finish");
            parts.settings = settings;
        }
        self.finish()
    }
}

#[doc(hidden)]
impl<S: 'static> Iterator for App<S> {
    type Item = HttpApplication<S>;

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


#[cfg(test)]
mod tests {
    use http::StatusCode;
    use super::*;
    use test::TestRequest;
    use httprequest::HttpRequest;
    use httpresponse::HttpResponse;

    #[test]
    fn test_default_resource() {
        let mut app = App::new()
            .resource("/test", |r| r.f(|_| HttpResponse::Ok()))
            .finish();

        let req = TestRequest::with_uri("/test").finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::OK);

        let req = TestRequest::with_uri("/blah").finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::NOT_FOUND);

        let mut app = App::new()
            .default_resource(|r| r.f(|_| HttpResponse::MethodNotAllowed()))
            .finish();
        let req = TestRequest::with_uri("/blah").finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::METHOD_NOT_ALLOWED);
    }

    #[test]
    fn test_unhandled_prefix() {
        let mut app = App::new()
            .prefix("/test")
            .resource("/test", |r| r.f(|_| HttpResponse::Ok()))
            .finish();
        assert!(app.handle(HttpRequest::default()).is_err());
    }

    #[test]
    fn test_state() {
        let mut app = App::with_state(10)
            .resource("/", |r| r.f(|_| HttpResponse::Ok()))
            .finish();
        let req = HttpRequest::default().with_state(Rc::clone(&app.state), app.router.clone());
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::OK);
    }

    #[test]
    fn test_prefix() {
        let mut app = App::new()
            .prefix("/test")
            .resource("/blah", |r| r.f(|_| HttpResponse::Ok()))
            .finish();
        let req = TestRequest::with_uri("/test").finish();
        let resp = app.handle(req);
        assert!(resp.is_ok());

        let req = TestRequest::with_uri("/test/").finish();
        let resp = app.handle(req);
        assert!(resp.is_ok());

        let req = TestRequest::with_uri("/test/blah").finish();
        let resp = app.handle(req);
        assert!(resp.is_ok());

        let req = TestRequest::with_uri("/testing").finish();
        let resp = app.handle(req);
        assert!(resp.is_err());
    }

    #[test]
    fn test_handler() {
        let mut app = App::new()
            .handler("/test", |_| HttpResponse::Ok())
            .finish();

        let req = TestRequest::with_uri("/test").finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::OK);

        let req = TestRequest::with_uri("/test/").finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::OK);

        let req = TestRequest::with_uri("/test/app").finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::OK);

        let req = TestRequest::with_uri("/testapp").finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::NOT_FOUND);

        let req = TestRequest::with_uri("/blah").finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::NOT_FOUND);
    }

    #[test]
    fn test_handler2() {
        let mut app = App::new()
            .handler("test", |_| HttpResponse::Ok())
            .finish();

        let req = TestRequest::with_uri("/test").finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::OK);

        let req = TestRequest::with_uri("/test/").finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::OK);

        let req = TestRequest::with_uri("/test/app").finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::OK);

        let req = TestRequest::with_uri("/testapp").finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::NOT_FOUND);

        let req = TestRequest::with_uri("/blah").finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::NOT_FOUND);
    }

    #[test]
    fn test_handler_with_prefix() {
        let mut app = App::new()
            .prefix("prefix")
            .handler("/test", |_| HttpResponse::Ok())
            .finish();

        let req = TestRequest::with_uri("/prefix/test").finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::OK);

        let req = TestRequest::with_uri("/prefix/test/").finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::OK);

        let req = TestRequest::with_uri("/prefix/test/app").finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::OK);

        let req = TestRequest::with_uri("/prefix/testapp").finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::NOT_FOUND);

        let req = TestRequest::with_uri("/prefix/blah").finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::NOT_FOUND);
    }

    #[test]
    fn test_route() {
        let mut app = App::new()
            .route("/test", Method::GET, |_: HttpRequest| HttpResponse::Ok())
            .route("/test", Method::POST, |_: HttpRequest| HttpResponse::Created())
            .finish();

        let req = TestRequest::with_uri("/test").method(Method::GET).finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::OK);

        let req = TestRequest::with_uri("/test").method(Method::POST).finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::CREATED);

        let req = TestRequest::with_uri("/test").method(Method::HEAD).finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::NOT_FOUND);
    }

    #[test]
    fn test_handler_prefix() {
        let mut app = App::new()
            .prefix("/app")
            .handler("/test", |_| HttpResponse::Ok())
            .finish();

        let req = TestRequest::with_uri("/test").finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::NOT_FOUND);

        let req = TestRequest::with_uri("/app/test").finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::OK);

        let req = TestRequest::with_uri("/app/test/").finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::OK);

        let req = TestRequest::with_uri("/app/test/app").finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::OK);

        let req = TestRequest::with_uri("/app/testapp").finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::NOT_FOUND);

        let req = TestRequest::with_uri("/app/blah").finish();
        let resp = app.run(req);
        assert_eq!(resp.as_response().unwrap().status(), StatusCode::NOT_FOUND);

    }

}