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
use std::any::Any;
use std::collections::HashMap;
use std::fmt::Debug;
use std::sync::Arc;

use crate::{
    configuration::Store,
    endpoint::{BoxedEndpoint, Endpoint},
    Middleware,
};
use path_table::{PathTable, RouteMatch};

/// A core type for routing.
///
/// The `Router` type can be used to set up routes and resources, and to apply middleware.
pub struct Router<Data> {
    table: PathTable<ResourceData<Data>>,
    middleware_base: Vec<Arc<dyn Middleware<Data> + Send + Sync>>,
    pub(crate) store_base: Store,
}

pub(crate) struct RouteResult<'a, Data> {
    pub(crate) endpoint: &'a EndpointData<Data>,
    pub(crate) params: Option<RouteMatch<'a>>,
    pub(crate) middleware: &'a [Arc<dyn Middleware<Data> + Send + Sync>],
}

fn route_match_success<'a, Data>(
    route: &'a ResourceData<Data>,
    route_match: RouteMatch<'a>,
    method: &http::Method,
) -> Option<RouteResult<'a, Data>> {
    // If it is a HTTP HEAD request then check if there is a callback in the endpoints map
    // if not then fallback to the behavior of HTTP GET else proceed as usual
    let endpoint =
        if method == http::Method::HEAD && !route.endpoints.contains_key(&http::Method::HEAD) {
            route.endpoints.get(&http::Method::GET)?
        } else {
            route.endpoints.get(method)?
        };
    let middleware = &*route.middleware;

    Some(RouteResult {
        endpoint,
        params: Some(route_match),
        middleware,
    })
}

fn route_match_failure<'a, Data>(
    endpoint: &'a EndpointData<Data>,
    middleware: &'a [Arc<dyn Middleware<Data> + Send + Sync>],
) -> RouteResult<'a, Data> {
    RouteResult {
        endpoint,
        params: None,
        middleware: &*middleware,
    }
}

impl<Data: Clone + Send + Sync + 'static> Router<Data> {
    /// Add a new resource at the given `path`, relative to this router.
    ///
    /// Routing means mapping an HTTP request to an endpoint. Here Tide applies a "table of
    /// contents" approach, which makes it easy to see the overall app structure. Endpoints are
    /// selected solely by the path and HTTP method of a request: the path determines the resource
    /// and the HTTP verb the respective endpoint of the selected resource. Example:
    ///
    /// ```rust,no_run
    /// # #![feature(async_await)]
    /// # let mut app = tide::App::new(());
    /// app.at("/").get(async || "Hello, world!");
    /// ```
    ///
    /// A path is comprised of zero or many segments, i.e. non-empty strings separated by '/'. There
    /// are two kinds of segments: concrete and wildcard. A concrete segment is used to exactly
    /// match the respective part of the path of the incoming request. A wildcard segment on the
    /// other hand extracts and parses the respective part of the path of the incoming request to
    /// pass it along to the endpoint as an argument. A wildcard segment is either defined by "{}"
    /// or by "{name}" for a so called named wildcard segment which can be extracted using
    /// `NamedSegment`. It is not possible to define wildcard segments with different names for
    /// otherwise identical paths.
    ///
    /// Wildcard definitions can be followed by an optional *wildcard modifier*. Currently, there is
    /// only one modifier: `*`, which means that the wildcard will match to the end of given path,
    /// no matter how many segments are left, even nothing. If there is a modifier for unnamed
    /// wildcard definition, `{}` may be omitted. That is, `{}*` can be written as `*`. It is an
    /// error to define two wildcard segments with different wildcard modifiers, or to write other
    /// path segment after a segment with wildcard modifier.
    ///
    /// Here are some examples omitting the HTTP verb based endpoint selection:
    ///
    /// ```rust,no_run
    /// # let mut app = tide::App::new(());
    /// app.at("/");
    /// app.at("/hello");
    /// app.at("/message/{}");
    /// app.at("add_two/{num}");
    /// app.at("static/{path}*");
    /// app.at("single_page_app/*");
    /// ```
    ///
    /// Notice that there is no fallback route matching, i.e. either a resource is a full match or
    /// not, which means that the order of adding resources has no effect.
    pub fn at<'a>(&'a mut self, path: &'a str) -> Resource<'a, Data> {
        let table = self.table.setup_table(path);
        Resource {
            table,
            middleware_base: &self.middleware_base,
        }
    }

    /// Create a new top-level router.
    pub(crate) fn new() -> Router<Data> {
        Router {
            table: PathTable::new(),
            middleware_base: Vec::new(),
            store_base: Store::new(),
        }
    }

    /// Apply `middleware` to this router.
    ///
    /// Note that the order of nesting subrouters and applying middleware matters. If there are
    /// nested subrouters *before* the method call, the given middleware will be applied *after*
    /// the subrouter middleware.
    ///
    /// ```
    /// # #![feature(futures_api, async_await)]
    /// # fn passthrough_middleware<Data: Clone + Send>(
    /// #     ctx: tide::middleware::RequestContext<Data>,
    /// # ) -> futures::future::FutureObj<tide::Response> {
    /// #     ctx.next()
    /// # }
    /// # let mut app = tide::App::new(());
    /// # let router = app.router();
    /// router.at("a1").nest(|router| {
    /// #   let a = passthrough_middleware;
    ///     router.middleware(a);
    ///     router.at("").get(async || "A then B");
    /// });
    /// # let b = passthrough_middleware;
    /// router.middleware(b);
    /// router.at("a2").nest(|router| {
    /// #   let a = passthrough_middleware;
    ///     router.middleware(a);
    ///     router.at("").get(async || "B then A");
    /// });
    /// ```
    pub fn middleware(&mut self, middleware: impl Middleware<Data> + 'static) -> &mut Self {
        let middleware = Arc::new(middleware);
        for resource in self.table.iter_mut() {
            resource.middleware.push(middleware.clone());
        }
        self.middleware_base.push(middleware);
        self
    }

    /// Add a default configuration `item` for this router.
    ///
    /// The default configuration will be applied when the router setup ends.
    pub fn config<T: Any + Debug + Clone + Send + Sync>(&mut self, item: T) -> &mut Self {
        self.store_base.write(item);
        self
    }

    pub(crate) fn route<'a>(
        &'a self,
        path: &'a str,
        method: &http::Method,
        default_handler: &'a Arc<EndpointData<Data>>,
    ) -> RouteResult<'a, Data> {
        match self.table.route(path) {
            Some((route, route_match)) => route_match_success(route, route_match, method)
                .unwrap_or_else(|| route_match_failure(default_handler, &self.middleware_base)),
            None => route_match_failure(default_handler, &self.middleware_base),
        }
    }
}

impl<Data> Router<Data> {
    pub(crate) fn apply_default_config(&mut self) {
        for resource in self.table.iter_mut() {
            for endpoint in resource.endpoints.values_mut() {
                endpoint.store.merge(&self.store_base);
            }
        }
    }

    pub(crate) fn get_item<T: Any + Debug + Clone + Send + Sync>(&self) -> Option<&T> {
        self.store_base.read()
    }
}

/// A handle to the endpoint.
///
/// This can be used to add configuration items to the endpoint.
pub struct EndpointData<Data> {
    pub(crate) endpoint: BoxedEndpoint<Data>,
    pub(crate) store: Store,
}

impl<Data> EndpointData<Data> {
    /// Add a configuration `item` for this endpoint.
    pub fn config<T: Any + Debug + Clone + Send + Sync>(&mut self, item: T) -> &mut Self {
        self.store.write(item);
        self
    }
}

/// A handle to a resource (identified by a path).
///
/// All HTTP requests are made against resources. After using `Router::at` (or `App::at`) to
/// establish a resource path, the `Resource` type can be used to establish endpoints for various
/// HTTP methods at that path. Also, using `nest`, it can be used to set up a subrouter.
///
/// After establishing an endpoint, the method will return `&mut EndpointData`. This can be used to
/// set per-endpoint configuration.
pub struct Resource<'a, Data> {
    table: &'a mut PathTable<ResourceData<Data>>,
    middleware_base: &'a Vec<Arc<dyn Middleware<Data> + Send + Sync>>,
}

struct ResourceData<Data> {
    endpoints: HashMap<http::Method, EndpointData<Data>>,
    middleware: Vec<Arc<dyn Middleware<Data> + Send + Sync>>,
}

impl<'a, Data> Resource<'a, Data> {
    /// "Nest" a subrouter to the path.
    ///
    /// This method will build a fresh `Router` and give a mutable reference to it to the builder
    /// function. Builder can set up a subrouter using the `Router`. All middleware applied inside
    /// the builder will be local to the subrouter and its descendents.
    ///
    /// If resources are already present, they will be discarded.
    pub fn nest(self, builder: impl FnOnce(&mut Router<Data>)) {
        let mut subrouter = Router {
            table: PathTable::new(),
            middleware_base: self.middleware_base.clone(),
            store_base: Store::new(),
        };
        builder(&mut subrouter);
        subrouter.apply_default_config();
        *self.table = subrouter.table;
    }

    /// Add an endpoint for the given HTTP method
    pub fn method<T: Endpoint<Data, U>, U>(
        &mut self,
        method: http::Method,
        ep: T,
    ) -> &mut EndpointData<Data> {
        let resource = self.table.resource_mut();
        if resource.is_none() {
            let new_resource = ResourceData {
                endpoints: HashMap::new(),
                middleware: self.middleware_base.clone(),
            };
            *resource = Some(new_resource);
        }
        let resource = resource.as_mut().unwrap();

        let entry = resource.endpoints.entry(method);
        if let std::collections::hash_map::Entry::Occupied(ep) = entry {
            panic!("A {} endpoint already exists for this path", ep.key())
        }

        let endpoint = EndpointData {
            endpoint: BoxedEndpoint::new(ep),
            store: Store::new(),
        };

        entry.or_insert(endpoint)
    }

    /// Add an endpoint for `GET` requests
    pub fn get<T: Endpoint<Data, U>, U>(&mut self, ep: T) -> &mut EndpointData<Data> {
        self.method(http::Method::GET, ep)
    }

    /// Add an endpoint for `HEAD` requests
    pub fn head<T: Endpoint<Data, U>, U>(&mut self, ep: T) -> &mut EndpointData<Data> {
        self.method(http::Method::HEAD, ep)
    }

    /// Add an endpoint for `PUT` requests
    pub fn put<T: Endpoint<Data, U>, U>(&mut self, ep: T) -> &mut EndpointData<Data> {
        self.method(http::Method::PUT, ep)
    }

    /// Add an endpoint for `POST` requests
    pub fn post<T: Endpoint<Data, U>, U>(&mut self, ep: T) -> &mut EndpointData<Data> {
        self.method(http::Method::POST, ep)
    }

    /// Add an endpoint for `DELETE` requests
    pub fn delete<T: Endpoint<Data, U>, U>(&mut self, ep: T) -> &mut EndpointData<Data> {
        self.method(http::Method::DELETE, ep)
    }

    /// Add an endpoint for `OPTIONS` requests
    pub fn options<T: Endpoint<Data, U>, U>(&mut self, ep: T) -> &mut EndpointData<Data> {
        self.method(http::Method::OPTIONS, ep)
    }

    /// Add an endpoint for `CONNECT` requests
    pub fn connect<T: Endpoint<Data, U>, U>(&mut self, ep: T) -> &mut EndpointData<Data> {
        self.method(http::Method::CONNECT, ep)
    }

    /// Add an endpoint for `PATCH` requests
    pub fn patch<T: Endpoint<Data, U>, U>(&mut self, ep: T) -> &mut EndpointData<Data> {
        self.method(http::Method::PATCH, ep)
    }

    /// Add an endpoint for `TRACE` requests
    pub fn trace<T: Endpoint<Data, U>, U>(&mut self, ep: T) -> &mut EndpointData<Data> {
        self.method(http::Method::TRACE, ep)
    }
}

#[cfg(test)]
mod tests {
    use futures::{executor::block_on, future::FutureObj};

    use super::*;
    use crate::{body::Body, middleware::RequestContext, AppData, Response};

    fn passthrough_middleware<Data: Clone + Send>(
        ctx: RequestContext<Data>,
    ) -> FutureObj<Response> {
        ctx.next()
    }

    async fn simulate_request<'a, Data: Default + Clone + Send + Sync + 'static>(
        router: &'a Router<Data>,
        path: &'a str,
        method: &'a http::Method,
    ) -> Option<Response> {
        let default_handler = Arc::new(EndpointData {
            endpoint: BoxedEndpoint::new(async || http::status::StatusCode::NOT_FOUND),
            store: Store::new(),
        });
        let RouteResult {
            endpoint,
            params,
            middleware,
        } = router.route(path, method, &default_handler);

        let data = Data::default();
        let req = http::Request::builder()
            .method(method)
            .body(Body::empty())
            .unwrap();

        let ctx = RequestContext {
            app_data: data,
            req,
            params,
            endpoint,
            next_middleware: middleware,
        };
        let res = await!(ctx.next());
        Some(res.map(Into::into))
    }

    fn route_middleware_count<Data: Clone + Send + Sync + 'static>(
        router: &Router<Data>,
        path: &str,
        method: &http::Method,
    ) -> Option<usize> {
        let default_handler = Arc::new(EndpointData {
            endpoint: BoxedEndpoint::new(async || http::status::StatusCode::NOT_FOUND),
            store: Store::new(),
        });
        let route_result = router.route(path, method, &default_handler);
        Some(route_result.middleware.len())
    }

    #[test]
    fn simple_static() {
        let mut router: Router<()> = Router::new();
        router.at("/").get(async || "/");
        router.at("/foo").get(async || "/foo");
        router.at("/foo/bar").get(async || "/foo/bar");

        for path in &["/", "/foo", "/foo/bar"] {
            let res =
                if let Some(res) = block_on(simulate_request(&router, path, &http::Method::GET)) {
                    res
                } else {
                    panic!("Routing of path `{}` failed", path);
                };
            let body =
                block_on(res.into_body().read_to_vec()).expect("Reading body should succeed");
            assert_eq!(&*body, path.as_bytes());
        }
    }

    #[test]
    fn nested_static() {
        let mut router: Router<()> = Router::new();
        router.at("/a").get(async || "/a");
        router.at("/b").nest(|router| {
            router.at("/").get(async || "/b");
            router.at("/a").get(async || "/b/a");
            router.at("/b").get(async || "/b/b");
            router.at("/c").nest(|router| {
                router.at("/a").get(async || "/b/c/a");
                router.at("/b").get(async || "/b/c/b");
            });
            router.at("/d").get(async || "/b/d");
        });
        router.at("/a/a").nest(|router| {
            router.at("/a").get(async || "/a/a/a");
            router.at("/b").get(async || "/a/a/b");
        });
        router.at("/a/b").nest(|router| {
            router.at("/").get(async || "/a/b");
        });

        for failing_path in &["/", "/a/a", "/a/b/a"] {
            if let Some(res) = block_on(simulate_request(&router, failing_path, &http::Method::GET))
            {
                if !res.status().is_client_error() {
                    panic!(
                        "Should have returned a client error when router cannot match with path {}",
                        failing_path
                    );
                }
            } else {
                panic!("Should have received a response from {}", failing_path);
            };
        }

        for path in &[
            "/a", "/a/a/a", "/a/a/b", "/a/b", "/b", "/b/a", "/b/b", "/b/c/a", "/b/c/b", "/b/d",
        ] {
            let res =
                if let Some(res) = block_on(simulate_request(&router, path, &http::Method::GET)) {
                    res
                } else {
                    panic!("Routing of path `{}` failed", path);
                };
            let body =
                block_on(res.into_body().read_to_vec()).expect("Reading body should succeed");
            assert_eq!(&*body, path.as_bytes());
        }
    }

    #[test]
    fn multiple_methods() {
        let mut router: Router<()> = Router::new();
        router.at("/a").nest(|router| {
            router.at("/b").get(async || "/a/b GET");
        });
        router.at("/a/b").post(async || "/a/b POST");

        for (path, method) in &[("/a/b", http::Method::GET), ("/a/b", http::Method::POST)] {
            let res = if let Some(res) = block_on(simulate_request(&router, path, &method)) {
                res
            } else {
                panic!("Routing of {} `{}` failed", method, path);
            };
            let body =
                block_on(res.into_body().read_to_vec()).expect("Reading body should succeed");
            assert_eq!(&*body, format!("{} {}", path, method).as_bytes());
        }
    }

    #[test]
    #[should_panic]
    fn duplicate_endpoint_fails() {
        let mut router: Router<()> = Router::new();
        router.at("/a").nest(|router| {
            router.at("/b").get(async || "");
        }); // flattened into /a/b
        router.at("/a/b").get(async || "duplicate");
    }

    #[test]
    fn simple_middleware() {
        let mut router: Router<()> = Router::new();
        router.middleware(passthrough_middleware);
        router.at("/").get(async || "/");
        router.at("/b").nest(|router| {
            router.at("/").get(async || "/b");
            router.middleware(passthrough_middleware);
        });

        assert_eq!(
            route_middleware_count(&router, "/", &http::Method::GET),
            Some(1)
        );
        assert_eq!(
            route_middleware_count(&router, "/b", &http::Method::GET),
            Some(2)
        );
    }

    #[test]
    fn middleware_apply_order() {
        #[derive(Default, Clone, Debug)]
        struct Data(Vec<usize>);
        struct Pusher(usize);
        impl Middleware<Data> for Pusher {
            fn handle<'a>(&'a self, mut ctx: RequestContext<'a, Data>) -> FutureObj<'a, Response> {
                FutureObj::new(Box::new(
                    async move {
                        ctx.app_data.0.push(self.0);
                        await!(ctx.next())
                    },
                ))
            }
        }

        // The order of endpoint and middleware does not matter
        // The order of subrouter and middleware DOES matter
        let mut router: Router<Data> = Router::new();
        router.middleware(Pusher(0));
        router.at("/").get(async move |data: AppData<Data>| {
            if (data.0).0 == [0, 2] {
                http::StatusCode::OK
            } else {
                http::StatusCode::INTERNAL_SERVER_ERROR
            }
        });
        router.at("/a").nest(|router| {
            router.at("/").get(async move |data: AppData<Data>| {
                if (data.0).0 == [0, 1, 2] {
                    http::StatusCode::OK
                } else {
                    http::StatusCode::INTERNAL_SERVER_ERROR
                }
            });
            router.middleware(Pusher(1));
        });
        router.middleware(Pusher(2));
        router.at("/b").nest(|router| {
            router.at("/").get(async move |data: AppData<Data>| {
                if (data.0).0 == [0, 2, 1] {
                    http::StatusCode::OK
                } else {
                    http::StatusCode::INTERNAL_SERVER_ERROR
                }
            });
            router.middleware(Pusher(1));
        });

        for path in &["/", "/a", "/b"] {
            let res = block_on(simulate_request(&router, path, &http::Method::GET)).unwrap();
            assert_eq!(res.status(), 200);
        }
    }

    #[test]
    fn configuration() {
        use crate::ExtractConfiguration;
        async fn endpoint(
            ExtractConfiguration(x): ExtractConfiguration<&'static str>,
        ) -> &'static str {
            x.unwrap()
        }

        let mut router: Router<()> = Router::new();
        router.config("foo");
        router.at("/").get(endpoint);
        router.at("/bar").get(endpoint).config("bar");
        router.apply_default_config(); // simulating App behavior

        let res = block_on(simulate_request(&router, "/", &http::Method::GET)).unwrap();
        let body = block_on(res.into_body().read_to_vec()).unwrap();
        assert_eq!(&*body, &*b"foo");

        let res = block_on(simulate_request(&router, "/bar", &http::Method::GET)).unwrap();
        let body = block_on(res.into_body().read_to_vec()).unwrap();
        assert_eq!(&*body, &*b"bar");
    }

    #[test]
    fn configuration_nested() {
        use crate::ExtractConfiguration;
        async fn endpoint(
            ExtractConfiguration(x): ExtractConfiguration<&'static str>,
        ) -> &'static str {
            x.unwrap()
        }

        let mut router: Router<()> = Router::new();
        router.config("foo");
        router.at("/").get(endpoint);
        router.at("/bar").nest(|router| {
            router.config("bar");
            router.at("/").get(endpoint);
            router.at("/baz").get(endpoint).config("baz");
        });
        router.apply_default_config(); // simulating App behavior

        let res = block_on(simulate_request(&router, "/", &http::Method::GET)).unwrap();
        let body = block_on(res.into_body().read_to_vec()).unwrap();
        assert_eq!(&*body, &*b"foo");

        let res = block_on(simulate_request(&router, "/bar", &http::Method::GET)).unwrap();
        let body = block_on(res.into_body().read_to_vec()).unwrap();
        assert_eq!(&*body, &*b"bar");

        let res = block_on(simulate_request(&router, "/bar/baz", &http::Method::GET)).unwrap();
        let body = block_on(res.into_body().read_to_vec()).unwrap();
        assert_eq!(&*body, &*b"baz");
    }

    #[test]
    fn configuration_order() {
        use crate::ExtractConfiguration;
        async fn endpoint(
            ExtractConfiguration(x): ExtractConfiguration<&'static str>,
        ) -> &'static str {
            x.unwrap()
        }

        let mut router: Router<()> = Router::new();
        router.at("/").get(endpoint);
        router.config("foo"); // order does not matter
        router.at("/bar").get(endpoint).config("bar");
        router.apply_default_config(); // simulating App behavior

        let res = block_on(simulate_request(&router, "/", &http::Method::GET)).unwrap();
        let body = block_on(res.into_body().read_to_vec()).unwrap();
        assert_eq!(&*body, &*b"foo");

        let res = block_on(simulate_request(&router, "/bar", &http::Method::GET)).unwrap();
        let body = block_on(res.into_body().read_to_vec()).unwrap();
        assert_eq!(&*body, &*b"bar");
    }
}