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
//! Defines a builder API for constructing a `Router`.

mod associated;
mod draw;
mod modify;
mod single;

use std::marker::PhantomData;
use std::panic::RefUnwindSafe;

use hyper::{Body, StatusCode};

use crate::extractor::{
    NoopPathExtractor, NoopQueryStringExtractor, PathExtractor, QueryStringExtractor,
};
use crate::pipeline::{finalize_pipeline_set, new_pipeline_set, PipelineHandleChain, PipelineSet};
use crate::router::response::{ResponseExtender, ResponseFinalizerBuilder};
use crate::router::route::dispatch::DispatcherImpl;
use crate::router::route::matcher::{AndRouteMatcher, RouteMatcher};
use crate::router::route::{Delegation, Extractors, RouteImpl};
use crate::router::tree::node::Node;
use crate::router::tree::Tree;
use crate::router::Router;

pub use self::associated::{AssociatedRouteBuilder, AssociatedSingleRouteBuilder};
pub use self::draw::DrawRoutes;
pub use self::modify::{ExtendRouteMatcher, ReplacePathExtractor, ReplaceQueryStringExtractor};
pub use self::single::DefineSingleRoute;

/// Builds a `Router` using the provided closure. Routes are defined using the `RouterBuilder`
/// value passed to the closure, and the `Router` is constructed before returning.
///
///
/// **Important note**: The `path` passed to the `RouterBuilder` is decomposed
/// in segments. This means that empty segments and trailing slashes are
/// removed. Basically `route.get("/foo//bar/baz/")` will have the same effect as
/// `route.get("/foo/bar/baz")`
///
/// ```rust
/// # use hyper::{Body, Response, StatusCode};
/// # use gotham::state::State;
/// # use gotham::router::Router;
/// # use gotham::router::builder::*;
/// # use gotham::pipeline::*;
/// # use gotham::middleware::session::{NewSessionMiddleware, SessionData};
/// # use gotham::test::TestServer;
/// # use serde::{Deserialize, Serialize};
/// #
/// # #[derive(Serialize, Deserialize, Default)]
/// # struct Session;
/// #
/// # fn my_handler(state: State) -> (State, Response<Body>) {
/// #   assert!(state.has::<SessionData<Session>>());
/// #   (state, Response::builder().status(StatusCode::ACCEPTED).body(Body::empty()).unwrap())
/// # }
/// #
/// fn router() -> Router {
///     let (chain, pipelines) = single_pipeline(
///         new_pipeline()
///             .add(NewSessionMiddleware::default().with_session_type::<Session>())
///             .build()
///     );
///
///     build_router(chain, pipelines, |route| {
///         route.get("/request/path").to(my_handler);
///     })
/// }
/// #
/// # fn main() {
/// #   let test_server = TestServer::new(router()).unwrap();
/// #   let response = test_server.client()
/// #       .get("https://example.com/request/path")
/// #       .perform()
/// #       .unwrap();
/// #   assert_eq!(response.status(), StatusCode::ACCEPTED);
/// # }
/// ```
pub fn build_router<C, P, F>(pipeline_chain: C, pipelines: PipelineSet<P>, f: F) -> Router
where
    C: PipelineHandleChain<P> + Copy + Send + Sync + 'static,
    P: Send + Sync + 'static,
    F: FnOnce(&mut RouterBuilder<C, P>),
{
    let mut tree = Tree::new();

    let response_finalizer = {
        let mut builder = RouterBuilder {
            node_builder: tree.borrow_root_mut(),
            pipeline_chain,
            pipelines,
            response_finalizer_builder: ResponseFinalizerBuilder::new(),
        };

        f(&mut builder);

        builder.response_finalizer_builder.finalize()
    };

    Router::new(tree, response_finalizer)
}

/// Builds a `Router` with **no** middleware using the provided closure. Routes are defined using
/// the `RouterBuilder` value passed to the closure, and the `Router` is constructed before
/// returning.
///
/// ```rust
/// # extern crate gotham;
/// # extern crate hyper;
/// #
/// # use hyper::{Body, Response, StatusCode};
/// # use gotham::state::State;
/// # use gotham::router::Router;
/// # use gotham::router::builder::*;
/// # use gotham::test::TestServer;
/// #
/// # fn my_handler(state: State) -> (State, Response<Body>) {
/// #   (state, Response::builder().status(StatusCode::ACCEPTED).body(Body::empty()).unwrap())
/// # }
/// #
/// fn router() -> Router {
///     build_simple_router(|route| {
///         route.get("/request/path").to(my_handler);
///     })
/// }
/// #
/// # fn main() {
/// #   let test_server = TestServer::new(router()).unwrap();
/// #   let response = test_server.client()
/// #       .get("https://example.com/request/path")
/// #       .perform()
/// #       .unwrap();
/// #   assert_eq!(response.status(), StatusCode::ACCEPTED);
/// # }
/// ```
pub fn build_simple_router<F>(f: F) -> Router
where
    F: FnOnce(&mut RouterBuilder<(), ()>),
{
    let pipelines = finalize_pipeline_set(new_pipeline_set());
    build_router((), pipelines, f)
}

/// The top-level builder which is created by `build_router` and passed to the provided closure.
/// See the `build_router` function and the `DrawRoutes` trait for usage.
pub struct RouterBuilder<'a, C, P>
where
    C: PipelineHandleChain<P> + Copy + Send + Sync + 'static,
    P: Send + Sync + 'static,
{
    node_builder: &'a mut Node,
    pipeline_chain: C,
    pipelines: PipelineSet<P>,
    response_finalizer_builder: ResponseFinalizerBuilder,
}

impl<'a, C, P> RouterBuilder<'a, C, P>
where
    C: PipelineHandleChain<P> + Copy + Send + Sync + 'static,
    P: Send + Sync + 'static,
{
    /// Adds a `ResponseExtender` to the `ResponseFinalizer` in the `Router`.
    ///
    /// ```rust
    /// # use hyper::{Body, Response, StatusCode};
    /// # use hyper::header::WARNING;
    /// # use gotham::state::State;
    /// # use gotham::router::Router;
    /// # use gotham::router::response::ResponseExtender;
    /// # use gotham::router::builder::*;
    /// # use gotham::test::TestServer;
    /// #
    /// # fn my_handler(state: State) -> (State, Response<Body>) {
    /// #   (state, Response::builder().status(StatusCode::INTERNAL_SERVER_ERROR).body(Body::empty()).unwrap())
    /// # }
    /// #
    /// struct MyExtender;
    ///
    /// impl ResponseExtender<Body> for MyExtender {
    ///     fn extend(&self, state: &mut State, response: &mut Response<Body>) {
    ///         // Extender implementation omitted.
    /// #       let _ = state;
    /// #       response.headers_mut().insert(WARNING, "299 example.com Deprecated".parse().unwrap());
    ///     }
    /// }
    ///
    /// fn router() -> Router {
    ///     build_simple_router(|route| {
    ///         route.add_response_extender(StatusCode::INTERNAL_SERVER_ERROR, MyExtender);
    /// #
    /// #       route.get("/").to(my_handler);
    ///     })
    /// }
    /// #
    /// # fn main() {
    /// #   let test_server = TestServer::new(router()).unwrap();
    /// #   let response = test_server.client()
    /// #       .get("https://example.com/")
    /// #       .perform()
    /// #       .unwrap();
    /// #   assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
    /// #
    /// #   {
    /// #       let warning = response.headers().get(WARNING).unwrap();
    /// #       assert_eq!(warning, "299 example.com Deprecated");
    /// #   }
    /// # }
    /// ```
    pub fn add_response_extender<E>(&mut self, status_code: StatusCode, extender: E)
    where
        E: ResponseExtender<Body> + Send + Sync + 'static,
    {
        self.response_finalizer_builder
            .add(status_code, Box::new(extender))
    }
}

/// A scoped builder, which is created by `DrawRoutes::scope` and passed to the provided closure.
/// The `DrawRoutes` trait has documentation for using this type.
pub struct ScopeBuilder<'a, C, P>
where
    C: PipelineHandleChain<P> + Copy + Send + Sync + 'static,
    P: Send + Sync + 'static,
{
    node_builder: &'a mut Node,
    pipeline_chain: C,
    pipelines: PipelineSet<P>,
}

/// A delegated builder, which is created by `DrawRoutes::delegate` and returned. The `DrawRoutes`
/// trait has documentation for using this type.
pub struct DelegateRouteBuilder<'a, M, C, P>
where
    M: RouteMatcher + Send + Sync + 'static,
    C: PipelineHandleChain<P> + Copy + Send + Sync + 'static,
    P: Send + Sync + 'static,
{
    matcher: M,
    node_builder: &'a mut Node,
    pipeline_chain: C,
    pipelines: PipelineSet<P>,
}

type DelegatedRoute<M> = RouteImpl<M, NoopPathExtractor, NoopQueryStringExtractor>;

impl<'a, M, C, P> DelegateRouteBuilder<'a, M, C, P>
where
    M: RouteMatcher + Send + Sync + 'static,
    C: PipelineHandleChain<P> + Copy + Send + Sync + 'static,
    P: RefUnwindSafe + Send + Sync + 'static,
{
    /// Directs the delegated route to the given `Router`.
    pub fn to_router(self, router: Router) {
        let dispatcher = DispatcherImpl::new(router, self.pipeline_chain, self.pipelines);
        let route: DelegatedRoute<M> = DelegatedRoute::new(
            self.matcher,
            Box::new(dispatcher),
            Extractors::new(),
            Delegation::External,
        );

        self.node_builder.add_route(Box::new(route));
    }

    /// Adds additional `RouteMatcher` requirements to the current delegate.
    pub fn add_route_matcher<NM: RouteMatcher + Send + Sync + 'static>(
        self,
        matcher: NM,
    ) -> DelegateRouteBuilder<'a, AndRouteMatcher<M, NM>, C, P> {
        DelegateRouteBuilder {
            matcher: AndRouteMatcher::<M, NM>::new(self.matcher, matcher),
            node_builder: self.node_builder,
            pipeline_chain: self.pipeline_chain,
            pipelines: self.pipelines,
        }
    }
}

/// Implements the traits required to define a single route, after determining which request paths
/// will be dispatched here. The `DefineSingleRoute` trait has documentation for using this type.
pub struct SingleRouteBuilder<'a, M, C, P, PE, QSE>
where
    M: RouteMatcher + Send + Sync + 'static,
    C: PipelineHandleChain<P> + Send + Sync + 'static,
    P: Send + Sync + 'static,
    PE: PathExtractor<Body> + Send + Sync + 'static,
    QSE: QueryStringExtractor<Body> + Send + Sync + 'static,
{
    node_builder: &'a mut Node,
    matcher: M,
    pipeline_chain: C,
    pipelines: PipelineSet<P>,
    phantom: PhantomData<(PE, QSE)>,
}

// Trait impls live with the traits.
impl<'a, M, C, P, PE, QSE> SingleRouteBuilder<'a, M, C, P, PE, QSE>
where
    M: RouteMatcher + Send + Sync + 'static,
    C: PipelineHandleChain<P> + Send + Sync + 'static,
    P: Send + Sync + 'static,
    PE: PathExtractor<Body> + Send + Sync + 'static,
    QSE: QueryStringExtractor<Body> + Send + Sync + 'static,
{
    /// Coerces the type of the internal `PhantomData`, to replace an extractor by changing the
    /// type parameter without changing anything else.
    fn coerce<NPE, NQSE>(self) -> SingleRouteBuilder<'a, M, C, P, NPE, NQSE>
    where
        NPE: PathExtractor<Body> + Send + Sync + 'static,
        NQSE: QueryStringExtractor<Body> + Send + Sync + 'static,
    {
        SingleRouteBuilder {
            node_builder: self.node_builder,
            matcher: self.matcher,
            pipeline_chain: self.pipeline_chain,
            pipelines: self.pipelines,
            phantom: PhantomData,
        }
    }
}

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

    use hyper::service::Service;
    use hyper::{body, Body, Request, Response, StatusCode};
    use serde::Deserialize;

    use crate::middleware::cookie::CookieParser;
    use crate::pipeline::new_pipeline;
    use crate::router::response::StaticResponseExtender;
    use crate::service::GothamService;
    use crate::state::{State, StateData};

    #[derive(Deserialize)]
    struct SalutationParams {
        name: String,
    }

    impl StateData for SalutationParams {}

    impl StaticResponseExtender for SalutationParams {
        type ResBody = Body;
        fn extend(_: &mut State, _: &mut Response<Body>) {}
    }

    #[derive(Deserialize)]
    struct AddParams {
        x: u64,
        y: u64,
    }

    impl StateData for AddParams {}

    impl StaticResponseExtender for AddParams {
        type ResBody = Body;
        fn extend(_: &mut State, _: &mut Response<Body>) {}
    }

    mod welcome {
        use super::*;
        pub(crate) fn index(state: State) -> (State, Response<Body>) {
            (
                state,
                Response::builder()
                    .status(StatusCode::OK)
                    .body(Body::empty())
                    .unwrap(),
            )
        }

        pub(crate) fn literal(state: State) -> (State, Response<Body>) {
            (
                state,
                Response::builder()
                    .status(StatusCode::CREATED)
                    .body(Body::empty())
                    .unwrap(),
            )
        }

        pub(crate) fn hello(mut state: State) -> (State, Response<Body>) {
            let params = state.take::<SalutationParams>();
            let response = Response::builder()
                .status(StatusCode::OK)
                .body(format!("Hello, {}!", params.name).into())
                .unwrap();
            (state, response)
        }

        pub(crate) fn globbed(state: State) -> (State, Response<Body>) {
            let response = Response::builder()
                .status(StatusCode::OK)
                .body("Globbed".into())
                .unwrap();
            (state, response)
        }

        pub(crate) fn delegated(state: State) -> (State, Response<Body>) {
            let response = Response::builder()
                .status(StatusCode::OK)
                .body("Delegated".into())
                .unwrap();
            (state, response)
        }

        pub(crate) fn goodbye(mut state: State) -> (State, Response<Body>) {
            let params = state.take::<SalutationParams>();
            let response = Response::builder()
                .status(StatusCode::OK)
                .body(format!("Goodbye, {}!", params.name).into())
                .unwrap();
            (state, response)
        }

        pub(crate) fn add(mut state: State) -> (State, Response<Body>) {
            let params = state.take::<AddParams>();
            let response = Response::builder()
                .status(StatusCode::OK)
                .body(format!("{} + {} = {}", params.x, params.y, params.x + params.y,).into())
                .unwrap();
            (state, response)
        }

        pub(crate) fn trailing_slash(state: State) -> (State, Response<Body>) {
            let response = Response::builder()
                .status(StatusCode::OK)
                .body("Trailing slash!".into())
                .unwrap();
            (state, response)
        }
    }

    mod resource {
        use super::*;
        pub(crate) fn create(state: State) -> (State, Response<Body>) {
            let response = Response::builder()
                .status(StatusCode::CREATED)
                .body(Body::empty())
                .unwrap();
            (state, response)
        }

        pub(crate) fn destroy(state: State) -> (State, Response<Body>) {
            let response = Response::builder()
                .status(StatusCode::ACCEPTED)
                .body(Body::empty())
                .unwrap();
            (state, response)
        }

        pub(crate) fn show(state: State) -> (State, Response<Body>) {
            let response = Response::builder()
                .status(StatusCode::OK)
                .body("It's a resource.".into())
                .unwrap();
            (state, response)
        }

        pub(crate) fn update(state: State) -> (State, Response<Body>) {
            let response = Response::builder()
                .status(StatusCode::ACCEPTED)
                .body(Body::empty())
                .unwrap();
            (state, response)
        }
    }

    mod api {
        use super::*;
        pub(crate) fn submit(state: State) -> (State, Response<Body>) {
            (
                state,
                Response::builder()
                    .status(StatusCode::ACCEPTED)
                    .body(Body::empty())
                    .unwrap(),
            )
        }
    }

    #[test]
    fn build_router_test() {
        let pipelines = new_pipeline_set();
        let (pipelines, default) = pipelines.add(new_pipeline().add(CookieParser).build());

        let pipelines = finalize_pipeline_set(pipelines);

        let default_pipeline_chain = (default, ());

        let delegated_router = build_simple_router(|route| {
            route.get("/b").to(welcome::delegated);
        });

        let router = build_router(default_pipeline_chain, pipelines, |route| {
            route.get("/").to(welcome::index);

            route
                .get("/hello/:name")
                .with_path_extractor::<SalutationParams>()
                .to(welcome::hello);

            route
                .get("/hello/:name/*")
                .with_path_extractor::<SalutationParams>()
                .to(welcome::globbed);

            route
                .get("/goodbye/:name:[a-zA-Z]+")
                .with_path_extractor::<SalutationParams>()
                .to(welcome::goodbye);

            route
                .get("/add")
                .with_query_string_extractor::<AddParams>()
                .to(welcome::add);

            route.get(r"/literal/\:param/\*").to(welcome::literal);

            route.scope("/api", |route| {
                route.post("/submit").to(api::submit);
            });

            route.associate("/resource", |route| {
                route.post().to(resource::create);
                route.patch().to(resource::update);
                route.delete().to(resource::destroy);
                route.get_or_head().to(resource::show);
            });

            route.delegate("/delegated").to_router(delegated_router);

            route.get("/trailing-slash/").to(welcome::trailing_slash);
        });

        let new_service = GothamService::new(router);

        let call = move |req| {
            let mut service = new_service.connect("127.0.0.1:10000".parse().unwrap());
            futures_executor::block_on(service.call(req)).unwrap()
        };

        let response = call(Request::get("/").body(Body::empty()).unwrap());
        assert_eq!(response.status(), StatusCode::OK);

        let response = call(Request::post("/api/submit").body(Body::empty()).unwrap());
        assert_eq!(response.status(), StatusCode::ACCEPTED);

        let response = call(Request::get("/hello/world").body(Body::empty()).unwrap());
        assert_eq!(response.status(), StatusCode::OK);
        let response_bytes = futures_executor::block_on(body::to_bytes(response.into_body()))
            .unwrap()
            .to_vec();
        assert_eq!(&String::from_utf8(response_bytes).unwrap(), "Hello, world!");

        let response = call(
            Request::get("/hello/world/more/path/here/handled/by/glob")
                .body(Body::empty())
                .unwrap(),
        );
        assert_eq!(response.status(), StatusCode::OK);
        let response_bytes = futures_executor::block_on(body::to_bytes(response.into_body()))
            .unwrap()
            .to_vec();
        assert_eq!(&String::from_utf8(response_bytes).unwrap(), "Globbed");

        let response = call(Request::get("/delegated/b").body(Body::empty()).unwrap());
        assert_eq!(response.status(), StatusCode::OK);
        let response_bytes = futures_executor::block_on(body::to_bytes(response.into_body()))
            .unwrap()
            .to_vec();
        assert_eq!(&String::from_utf8(response_bytes).unwrap(), "Delegated");

        let response = call(Request::get("/goodbye/world").body(Body::empty()).unwrap());
        assert_eq!(response.status(), StatusCode::OK);
        let response_bytes = futures_executor::block_on(body::to_bytes(response.into_body()))
            .unwrap()
            .to_vec();
        assert_eq!(
            &String::from_utf8(response_bytes).unwrap(),
            "Goodbye, world!"
        );

        let response = call(Request::get("/goodbye/9875").body(Body::empty()).unwrap());
        assert_eq!(response.status(), StatusCode::NOT_FOUND);

        let response = call(
            Request::get("/literal/:param/*")
                .body(Body::empty())
                .unwrap(),
        );
        assert_eq!(response.status(), StatusCode::CREATED);

        let response = call(Request::get("/literal/a/b").body(Body::empty()).unwrap());
        assert_eq!(response.status(), StatusCode::NOT_FOUND);

        let response = call(Request::get("/add?x=16&y=71").body(Body::empty()).unwrap());
        assert_eq!(response.status(), StatusCode::OK);
        let response_bytes = futures_executor::block_on(body::to_bytes(response.into_body()))
            .unwrap()
            .to_vec();
        assert_eq!(&String::from_utf8(response_bytes).unwrap(), "16 + 71 = 87");

        let response = call(Request::post("/resource").body(Body::empty()).unwrap());
        assert_eq!(response.status(), StatusCode::CREATED);

        let response = call(Request::patch("/resource").body(Body::empty()).unwrap());
        assert_eq!(response.status(), StatusCode::ACCEPTED);

        let response = call(Request::delete("/resource").body(Body::empty()).unwrap());
        assert_eq!(response.status(), StatusCode::ACCEPTED);

        let response = call(Request::get("/resource").body(Body::empty()).unwrap());
        assert_eq!(response.status(), StatusCode::OK);
        let response_bytes = futures_executor::block_on(body::to_bytes(response.into_body()))
            .unwrap()
            .to_vec();
        assert_eq!(&response_bytes[..], b"It's a resource.");

        let response = call(
            Request::get("/trailing-slash/")
                .body(Body::empty())
                .unwrap(),
        );
        assert_eq!(response.status(), StatusCode::OK);
        let response = call(Request::get("/trailing-slash").body(Body::empty()).unwrap());
        assert_eq!(response.status(), StatusCode::OK);
    }
}