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 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063
use std::marker::PhantomData;
use std::panic::RefUnwindSafe;
use hyper::Method;
use log::trace;
use crate::extractor::{NoopPathExtractor, NoopQueryStringExtractor};
use crate::helpers::http::request::path::split_path_segments;
use crate::pipeline::{PipelineHandleChain, PipelineSet};
use crate::router::builder::{
AssociatedRouteBuilder, DelegateRouteBuilder, RouterBuilder, ScopeBuilder, SingleRouteBuilder,
};
use crate::router::route::matcher::{
AnyRouteMatcher, IntoRouteMatcher, MethodOnlyRouteMatcher, RouteMatcher,
};
use crate::router::tree::node::Node;
use crate::router::tree::regex::ConstrainedSegmentRegex;
use crate::router::tree::segment::SegmentType;
/// The type returned when building a route that only considers path and http verb(s) when
/// determining if it matches a request.
///
/// See `router::builder::DefineSingleRoute` for an overview of route specification.
pub(crate) type DefaultSingleRouteBuilder<'a, C, P> = SingleRouteBuilder<
'a,
MethodOnlyRouteMatcher,
C,
P,
NoopPathExtractor,
NoopQueryStringExtractor,
>;
/// The type returned when building a route with explicit matching requirements.
///
/// See `router::builder::DefineSingleRoute` for an overview of route specification.
pub(crate) type ExplicitSingleRouteBuilder<'a, M, C, P> =
SingleRouteBuilder<'a, M, C, P, NoopPathExtractor, NoopQueryStringExtractor>;
/// The type passed to the function used when building associated routes. See
/// `AssociatedRouteBuilder` for information about the API available for associated routes.
pub(crate) type DefaultAssociatedRouteBuilder<'a, M, C, P> =
AssociatedRouteBuilder<'a, M, C, P, NoopPathExtractor, NoopQueryStringExtractor>;
/// Defines functions used by a builder to determine which request paths will be dispatched to a
/// route. This trait is implemented by the top-level `RouterBuilder`, and also the `ScopedBuilder`
/// created by `DrawRoutes::scope`.
pub trait DrawRoutes<C, P>
where
C: PipelineHandleChain<P> + Copy + Send + Sync + 'static,
P: RefUnwindSafe + Send + Sync + 'static,
{
/// Creates a route which matches `GET` and `HEAD` requests to the given path.
///
/// # Examples
///
/// ```rust
/// # 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_or_head("/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);
/// #
/// # let response = test_server.client()
/// # .head("https://example.com/request/path")
/// # .perform()
/// # .unwrap();
/// # assert_eq!(response.status(), StatusCode::ACCEPTED);
/// # }
/// ```
fn get_or_head<'b>(&'b mut self, path: &str) -> DefaultSingleRouteBuilder<'b, C, P> {
self.request(vec![Method::GET, Method::HEAD], path)
}
/// Creates a route which matches **only** `GET` requests to the given path (ignoring `HEAD`
/// requests).
///
/// # Examples
///
/// ```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);
/// # }
/// ```
fn get<'b>(&'b mut self, path: &str) -> DefaultSingleRouteBuilder<'b, C, P> {
self.request(vec![Method::GET], path)
}
/// Creates a route which matches `HEAD` requests to the given path.
///
/// # Examples
///
/// ```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.head("/request/path").to(my_handler);
/// })
/// # }
/// #
/// # fn main() {
/// # let test_server = TestServer::new(router()).unwrap();
/// # let response = test_server.client()
/// # .head("https://example.com/request/path")
/// # .perform()
/// # .unwrap();
/// # assert_eq!(response.status(), StatusCode::ACCEPTED);
/// # }
/// ```
fn head<'b>(&'b mut self, path: &str) -> DefaultSingleRouteBuilder<'b, C, P> {
self.request(vec![Method::HEAD], path)
}
/// Creates a route which matches `POST` requests to the given path.
///
/// # Examples
///
/// ```rust
/// # extern crate gotham;
/// # extern crate hyper;
/// # extern crate mime;
/// #
/// # 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.post("/request/path").to(my_handler);
/// })
/// # }
/// #
/// # fn main() {
/// # let test_server = TestServer::new(router()).unwrap();
/// # let response = test_server.client()
/// # .post("https://example.com/request/path", b"".to_vec(), mime::TEXT_PLAIN)
/// # .perform()
/// # .unwrap();
/// # assert_eq!(response.status(), StatusCode::ACCEPTED);
/// # }
/// ```
fn post<'b>(&'b mut self, path: &str) -> DefaultSingleRouteBuilder<'b, C, P> {
self.request(vec![Method::POST], path)
}
/// Creates a route which matches `PUT` requests to the given path.
///
/// # Examples
///
/// ```rust
/// # extern crate gotham;
/// # extern crate hyper;
/// # extern crate mime;
/// #
/// # 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.put("/request/path").to(my_handler);
/// })
/// # }
/// #
/// # fn main() {
/// # let test_server = TestServer::new(router()).unwrap();
/// # let response = test_server.client()
/// # .put("https://example.com/request/path", b"".to_vec(), mime::TEXT_PLAIN)
/// # .perform()
/// # .unwrap();
/// # assert_eq!(response.status(), StatusCode::ACCEPTED);
/// # }
/// ```
fn put<'b>(&'b mut self, path: &str) -> DefaultSingleRouteBuilder<'b, C, P> {
self.request(vec![Method::PUT], path)
}
/// Creates a route which matches `PATCH` requests to the given path.
///
/// # Examples
///
/// ```rust
/// # extern crate gotham;
/// # extern crate hyper;
/// # extern crate mime;
/// #
/// # 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.patch("/request/path").to(my_handler);
/// })
/// # }
/// #
/// # fn main() {
/// # let test_server = TestServer::new(router()).unwrap();
/// # let response = test_server.client()
/// # .patch("https://example.com/request/path", b"".to_vec(), mime::TEXT_PLAIN)
/// # .perform()
/// # .unwrap();
/// # assert_eq!(response.status(), StatusCode::ACCEPTED);
/// # }
/// ```
fn patch<'b>(&'b mut self, path: &str) -> DefaultSingleRouteBuilder<'b, C, P> {
self.request(vec![Method::PATCH], path)
}
/// Creates a route which matches `DELETE` requests to the given path.
///
/// # Examples
///
/// ```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.delete("/request/path").to(my_handler);
/// })
/// # }
/// #
/// # fn main() {
/// # let test_server = TestServer::new(router()).unwrap();
/// # let response = test_server.client()
/// # .delete("https://example.com/request/path")
/// # .perform()
/// # .unwrap();
/// # assert_eq!(response.status(), StatusCode::ACCEPTED);
/// # }
/// ```
fn delete<'b>(&'b mut self, path: &str) -> DefaultSingleRouteBuilder<'b, C, P> {
self.request(vec![Method::DELETE], path)
}
/// Creates a route which matches `OPTIONS` requests to the given path.
///
/// # Examples
///
/// ```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.options("/request/path").to(my_handler);
/// })
/// # }
/// #
/// # fn main() {
/// # let test_server = TestServer::new(router()).unwrap();
/// # let response = test_server.client()
/// # .options("https://example.com/request/path")
/// # .perform()
/// # .unwrap();
/// # assert_eq!(response.status(), StatusCode::ACCEPTED);
/// # }
/// ```
fn options<'b>(&'b mut self, path: &str) -> DefaultSingleRouteBuilder<'b, C, P> {
self.request(vec![Method::OPTIONS], path)
}
/// Creates a single route which matches any requests to the given `path` with one of the
/// given `methods`. The `path` can consist of static or dynamic segments, for example:
///
/// * `"/hello/world"` - a static path, matching only a request for exactly `"/hello/world"`
/// * `"/hello/:name"` - a dynamic path, matching requests for `"/hello/any_value_here"`
///
/// # Examples
///
/// ```rust
/// # extern crate gotham;
/// # extern crate hyper;
/// #
/// # use hyper::{Body, Response, StatusCode};
/// # use hyper::Method;
/// # 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.request(vec![Method::GET, Method::HEAD], "/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);
/// #
/// # let response = test_server.client()
/// # .head("https://example.com/request/path")
/// # .perform()
/// # .unwrap();
/// # assert_eq!(response.status(), StatusCode::ACCEPTED);
/// # }
/// ```
///
/// ```
/// # extern crate gotham;
/// # extern crate hyper;
/// # extern crate mime;
/// #
/// # use hyper::{Body, Response, StatusCode};
/// # use hyper::header::ACCEPT;
/// # use gotham::state::State;
/// # use gotham::router::route::matcher::AcceptHeaderRouteMatcher;
/// # 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| {
/// // All we match on is the Accept header, the method is not considered.
/// let matcher = AcceptHeaderRouteMatcher::new(vec![mime::APPLICATION_JSON]);
/// route.request(matcher, "/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")
/// # .with_header(ACCEPT, mime::APPLICATION_JSON.to_string().parse().unwrap())
/// # .perform()
/// # .unwrap();
/// # assert_eq!(response.status(), StatusCode::ACCEPTED);
/// #
/// # let response = test_server.client()
/// # .get("https://example.com/request/path")
/// # .with_header(ACCEPT, mime::TEXT_PLAIN.to_string().parse().unwrap())
/// # .perform()
/// # .unwrap();
/// # assert_eq!(response.status(), StatusCode::NOT_ACCEPTABLE);
/// #
/// # // No Accept type being provided is valid for the AcceptHeaderRouterMatcher
/// # // Proves the method is not considered
/// # let response = test_server.client()
/// # .delete("https://example.com/request/path")
/// # .perform()
/// # .unwrap();
/// # assert_eq!(response.status(), StatusCode::ACCEPTED);
/// # }
/// ```
fn request<'b, IRM, M>(
&'b mut self,
matcher: IRM,
path: &str,
) -> ExplicitSingleRouteBuilder<'b, M, C, P>
where
IRM: IntoRouteMatcher<Output = M>,
M: RouteMatcher + Send + Sync + 'static,
{
let (node_builder, pipeline_chain, pipelines) = self.component_refs();
let node_builder = descend(node_builder, path);
let matcher = matcher.into_route_matcher();
SingleRouteBuilder {
matcher,
node_builder,
pipeline_chain: *pipeline_chain,
pipelines: pipelines.clone(),
phantom: PhantomData,
}
}
/// Begins defining a new scope, based on a given `path` prefix.
///
/// # Examples
///
/// ```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;
/// #
/// # mod api {
/// # use super::*;
/// # pub fn list(state: State) -> (State, Response<Body>) {
/// # (state, Response::builder().status(StatusCode::ACCEPTED).body(Body::empty()).unwrap())
/// # }
/// # }
/// #
/// # fn router() -> Router {
/// build_simple_router(|route| {
/// route.scope("/api", |route| {
/// // Match requests to `/api/list`
/// route.get("/list").to(api::list);
/// });
/// })
/// # }
/// #
/// # fn main() {
/// # let test_server = TestServer::new(router()).unwrap();
/// # let response = test_server.client()
/// # .get("https://example.com/api/list")
/// # .perform()
/// # .unwrap();
/// # assert_eq!(response.status(), StatusCode::ACCEPTED);
/// # }
/// ```
fn scope<F>(&mut self, path: &str, f: F)
where
F: FnOnce(&mut ScopeBuilder<C, P>),
{
let (node_builder, pipeline_chain, pipelines) = self.component_refs();
let node_builder = descend(node_builder, path);
let mut scope_builder = ScopeBuilder {
node_builder,
pipeline_chain: *pipeline_chain,
pipelines: pipelines.clone(),
};
f(&mut scope_builder)
}
/// Begins a new scope at the current location, with an alternate pipeline chain.
///
/// # Examples
///
/// ```rust
/// # use hyper::{Body, Response, StatusCode};
/// # use gotham::state::State;
/// # use gotham::middleware::session::{NewSessionMiddleware, SessionData};
/// # use gotham::router::Router;
/// # use gotham::router::builder::*;
/// # use gotham::pipeline::{finalize_pipeline_set, new_pipeline_set, new_pipeline};
/// # use gotham::test::TestServer;
/// # use serde::{Deserialize, Serialize};
/// #
/// # #[derive(Default, Serialize, Deserialize)]
/// # struct Session;
/// #
/// # #[derive(Default, Serialize, Deserialize)]
/// # struct AdminSession;
/// #
/// # mod resource {
/// # use super::*;
/// # pub fn list(state: State) -> (State, Response<Body>) {
/// # assert!(state.has::<SessionData<Session>>());
/// # assert!(!state.has::<SessionData<AdminSession>>());
/// # (state, Response::builder().status(StatusCode::ACCEPTED).body(Body::empty()).unwrap())
/// # }
/// # }
/// #
/// # mod admin {
/// # use super::*;
/// # pub fn handler(state: State) -> (State, Response<Body>) {
/// # assert!(state.has::<SessionData<Session>>());
/// # assert!(state.has::<SessionData<AdminSession>>());
/// # (state, Response::builder().status(StatusCode::ACCEPTED).body(Body::empty()).unwrap())
/// # }
/// # }
/// #
/// # fn handler(state: State) -> (State, Response<Body>) {
/// # assert!(!state.has::<SessionData<Session>>());
/// # assert!(!state.has::<SessionData<AdminSession>>());
/// # (state, Response::builder().status(StatusCode::ACCEPTED).body(Body::empty()).unwrap())
/// # }
/// #
/// # fn router() -> Router {
/// let pipelines = new_pipeline_set();
/// let (pipelines, default) = pipelines.add(
/// new_pipeline()
/// .add(NewSessionMiddleware::default().with_session_type::<Session>())
/// .build()
/// );
/// let (pipelines, extended) = pipelines.add(
/// new_pipeline()
/// .add(NewSessionMiddleware::default().with_session_type::<AdminSession>())
/// .build()
/// );
/// let pipeline_set = finalize_pipeline_set(pipelines);
///
/// let default_chain = (default, ());
/// let extended_chain = (extended, default_chain);
///
/// build_router(default_chain, pipeline_set, |route| {
/// // Requests for the root handler use an empty set of pipelines, skipping the session
/// // middlewares.
/// route.with_pipeline_chain((), |route| {
/// route.get("/").to(handler);
/// });
///
/// // Requests dispatched to the resource module will only invoke one session
/// // middleware which is the default behavior.
/// route.get("/resource/list").to(resource::list);
///
/// // Requests for the admin handler will additionally invoke the admin session
/// // middleware.
/// route.with_pipeline_chain(extended_chain, |route| {
/// route.get("/admin").to(admin::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::ACCEPTED);
/// #
/// # let response = test_server.client()
/// # .get("https://example.com/resource/list")
/// # .perform()
/// # .unwrap();
/// # assert_eq!(response.status(), StatusCode::ACCEPTED);
/// # }
/// ```
fn with_pipeline_chain<F, NC>(&mut self, pipeline_chain: NC, f: F)
where
F: FnOnce(&mut ScopeBuilder<NC, P>),
NC: PipelineHandleChain<P> + Copy + Send + Sync + 'static,
{
let (node_builder, _pipeline_chain, pipelines) = self.component_refs();
let mut scope_builder = ScopeBuilder {
node_builder,
pipeline_chain,
pipelines: pipelines.clone(),
};
f(&mut scope_builder)
}
/// Begins delegating a subpath of the tree.
///
/// # Examples
///
/// ```rust
/// # extern crate gotham;
/// # extern crate hyper;
/// #
/// # use hyper::{Body, Response, StatusCode};
/// # use gotham::router::Router;
/// # use gotham::router::builder::*;
/// # use gotham::state::State;
/// # use gotham::test::TestServer;
/// #
/// fn admin_router() -> Router {
/// // Implementation elided
/// # fn handler(state: State) -> (State, Response<Body>) {
/// # (state, Response::builder().status(StatusCode::ACCEPTED).body(Body::empty()).unwrap())
/// # }
/// #
/// # build_simple_router(|route| {
/// # route.get("/").to(handler);
/// # })
/// }
///
/// # fn router() -> Router {
/// build_simple_router(|route| {
/// route.delegate("/admin").to_router(admin_router());
/// })
/// # }
/// #
/// # fn main() {
/// # let test_server = TestServer::new(router()).unwrap();
/// # let response = test_server.client()
/// # .get("https://example.com/admin")
/// # .perform()
/// # .unwrap();
/// # assert_eq!(response.status(), StatusCode::ACCEPTED);
/// # }
/// ```
fn delegate<'b>(&'b mut self, path: &str) -> DelegateRouteBuilder<'b, AnyRouteMatcher, C, P> {
let (node_builder, pipeline_chain, pipelines) = self.component_refs();
let node_builder = descend(node_builder, path);
DelegateRouteBuilder {
matcher: AnyRouteMatcher::new(),
node_builder,
pipeline_chain: *pipeline_chain,
pipelines: pipelines.clone(),
}
}
/// Begins delegating a subpath of the tree, but does not dispatch the requests via this
/// router's `PipelineChain`.
///
/// # Examples
///
/// ```rust
/// # use hyper::{Body, Response, StatusCode};
/// # use gotham::router::Router;
/// # use gotham::router::builder::*;
/// # use gotham::pipeline::{new_pipeline, single_pipeline};
/// # use gotham::state::State;
/// # use gotham::middleware::session::{NewSessionMiddleware, SessionData};
/// # use gotham::test::TestServer;
/// # use serde::{Deserialize, Serialize};
/// #
/// # #[derive(Default, Serialize, Deserialize)]
/// # struct Session;
/// #
/// // API routes which don't require sessions.
/// fn api_router() -> Router {
/// // Implementation elided
/// # fn handler(state: State) -> (State, Response<Body>) {
/// # assert!(!state.has::<SessionData<Session>>());
/// # (state, Response::builder().status(StatusCode::ACCEPTED).body(Body::empty()).unwrap())
/// # }
/// #
/// # build_simple_router(|route| {
/// # route.get("/").to(handler);
/// # })
/// }
/// # fn 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| {
/// // Requests dispatched to the `/api` router will not invoke the session middleware.
/// route.delegate_without_pipelines("/api").to_router(api_router());
///
/// // Other requests will invoke the session middleware as normal.
/// route.get("/").to(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::ACCEPTED);
/// #
/// # let response = test_server.client()
/// # .get("https://example.com/api")
/// # .perform()
/// # .unwrap();
/// # assert_eq!(response.status(), StatusCode::ACCEPTED);
/// # }
/// ```
fn delegate_without_pipelines<'b>(
&'b mut self,
path: &str,
) -> DelegateRouteBuilder<'b, AnyRouteMatcher, (), P> {
let (node_builder, _pipeline_chain, pipelines) = self.component_refs();
let node_builder = descend(node_builder, path);
DelegateRouteBuilder {
matcher: AnyRouteMatcher::new(),
node_builder,
pipeline_chain: (),
pipelines: pipelines.clone(),
}
}
/// Begins associating routes with a fixed path in the tree. In this way, multiple routes can
/// be quickly associated with a single location.
///
/// # Examples
///
/// ```rust
/// # extern crate gotham;
/// # extern crate hyper;
/// # extern crate mime;
/// #
/// # use hyper::{Body, Response, StatusCode};
/// # use gotham::router::Router;
/// # use gotham::router::builder::*;
/// # use gotham::state::State;
/// # use gotham::test::TestServer;
/// #
/// mod resource {
/// # use super::*;
/// pub fn show(state: State) -> (State, Response<Body>) {
/// // Implementation elided.
/// # (state, Response::builder().status(StatusCode::NO_CONTENT).body(Body::empty()).unwrap())
/// }
///
/// pub fn update(state: State) -> (State, Response<Body>) {
/// // Implementation elided.
/// # (state, Response::builder().status(StatusCode::CREATED).body(Body::empty()).unwrap())
/// }
///
/// pub fn delete(state: State) -> (State, Response<Body>) {
/// // Implementation elided.
/// # (state, Response::builder().status(StatusCode::ACCEPTED).body(Body::empty()).unwrap())
/// }
/// }
///
/// #
/// # fn router() -> Router {
/// build_simple_router(|route| {
/// route.associate("/resource", |assoc| {
/// assoc.get_or_head().to(resource::show);
/// assoc.patch().to(resource::update);
/// assoc.delete().to(resource::delete);
/// });
/// })
/// # }
/// #
/// # fn main() {
/// # let test_server = TestServer::new(router()).unwrap();
/// # let response = test_server.client()
/// # .get("https://example.com/resource")
/// # .perform()
/// # .unwrap();
/// # assert_eq!(response.status(), StatusCode::NO_CONTENT);
/// #
/// # let response = test_server.client()
/// # .patch("https://example.com/resource", b"".to_vec(), mime::TEXT_PLAIN)
/// # .perform()
/// # .unwrap();
/// # assert_eq!(response.status(), StatusCode::CREATED);
/// #
/// # let response = test_server.client()
/// # .delete("https://example.com/resource")
/// # .perform()
/// # .unwrap();
/// # assert_eq!(response.status(), StatusCode::ACCEPTED);
/// # }
/// ```
fn associate<'b, F>(&'b mut self, path: &str, f: F)
where
F: FnOnce(&mut DefaultAssociatedRouteBuilder<'b, AnyRouteMatcher, C, P>),
{
let (node_builder, pipeline_chain, pipelines) = self.component_refs();
let node_builder = descend(node_builder, path);
let mut builder =
AssociatedRouteBuilder::new(node_builder, *pipeline_chain, pipelines.clone());
f(&mut builder)
}
/// Return the components that comprise this builder. For internal use only.
#[doc(hidden)]
fn component_refs(&mut self) -> (&mut Node, &mut C, &PipelineSet<P>);
}
fn descend<'n>(node_builder: &'n mut Node, path: &str) -> &'n mut Node {
trace!("[walking to: {}]", path);
let path = path.strip_prefix('/').unwrap_or(path);
if path.is_empty() {
node_builder
} else {
build_subtree(node_builder, split_path_segments(path))
}
}
fn build_subtree<'n, 's, I>(node: &'n mut Node, mut i: I) -> &'n mut Node
where
I: Iterator<Item = &'s str>,
{
match i.next() {
Some(segment) => {
trace!("[descending into {}]", segment);
let (segment, segment_type) = match segment.chars().next() {
Some(':') => {
let segment = &segment[1..];
match segment.find(':') {
Some(n) => {
let (segment, pattern) = segment.split_at(n);
let regex = Box::new(ConstrainedSegmentRegex::new(&pattern[1..]));
(segment, SegmentType::Constrained { regex })
}
None => (segment, SegmentType::Dynamic),
}
}
Some('*') if segment.len() == 1 => (segment, SegmentType::Glob),
Some('*') => (&segment[1..], SegmentType::Glob),
Some('\\') => (&segment[1..], SegmentType::Static),
_ => (segment, SegmentType::Static),
};
if !node.has_child(segment, segment_type.clone()) {
node.add_child(Node::new(segment, segment_type.clone()));
}
let child = node.borrow_child_mut(segment, segment_type).unwrap();
build_subtree(child, i)
}
None => {
trace!("[reached node]");
node
}
}
}
impl<'a, C, P> DrawRoutes<C, P> for RouterBuilder<'a, C, P>
where
C: PipelineHandleChain<P> + Copy + Send + Sync + 'static,
P: RefUnwindSafe + Send + Sync + 'static,
{
fn component_refs(&mut self) -> (&mut Node, &mut C, &PipelineSet<P>) {
(
&mut self.node_builder,
&mut self.pipeline_chain,
&self.pipelines,
)
}
}
impl<'a, C, P> DrawRoutes<C, P> for ScopeBuilder<'a, C, P>
where
C: PipelineHandleChain<P> + Copy + Send + Sync + 'static,
P: RefUnwindSafe + Send + Sync + 'static,
{
fn component_refs(&mut self) -> (&mut Node, &mut C, &PipelineSet<P>) {
(
&mut self.node_builder,
&mut self.pipeline_chain,
&self.pipelines,
)
}
}
#[cfg(test)]
mod tests {
use std::pin::Pin;
use futures_util::future::{self, FutureExt};
use hyper::{Body, Response, StatusCode};
use crate::handler::HandlerFuture;
use crate::helpers::http::response::create_empty_response;
use crate::hyper::header::ACCEPT;
use crate::middleware::{Middleware, NewMiddleware};
use crate::pipeline::*;
use crate::router::builder::*;
use crate::router::route::matcher::AcceptHeaderRouteMatcher;
use crate::state::State;
use crate::test::TestServer;
#[derive(Clone, Copy)]
struct QuickExitMiddleware;
impl NewMiddleware for QuickExitMiddleware {
type Instance = Self;
fn new_middleware(&self) -> anyhow::Result<Self> {
Ok(*self)
}
}
impl Middleware for QuickExitMiddleware {
fn call<Chain>(self, state: State, _chain: Chain) -> Pin<Box<HandlerFuture>>
where
Chain: FnOnce(State) -> Pin<Box<HandlerFuture>> + 'static,
{
let f = future::ok((
state,
Response::builder()
.status(StatusCode::INTERNAL_SERVER_ERROR)
.body(Body::empty())
.unwrap(),
));
f.boxed()
}
}
fn test_handler(state: State) -> (State, Response<Body>) {
let response = create_empty_response(&state, StatusCode::ACCEPTED);
(state, response)
}
#[test]
fn delegate_with_matcher() {
let test_router = build_simple_router(|route| {
route.get("/").to(test_handler);
});
let router = build_simple_router(|route| {
let matcher = AcceptHeaderRouteMatcher::new(vec![mime::APPLICATION_JSON]);
route
.delegate("/test")
.add_route_matcher(matcher)
.to_router(test_router);
});
let test_server = TestServer::new(router).unwrap();
let response = test_server
.client()
.get("http://localhost/test/")
.with_header(ACCEPT, mime::JAVASCRIPT.to_string().parse().unwrap())
.perform()
.unwrap();
assert_eq!(response.status(), StatusCode::NOT_ACCEPTABLE);
let response = test_server
.client()
.get("http://localhost/test/")
.with_header(ACCEPT, mime::APPLICATION_JSON.to_string().parse().unwrap())
.perform()
.unwrap();
assert_eq!(response.status(), StatusCode::ACCEPTED);
}
#[test]
fn delegate_includes_pipelines() {
let (chain, pipelines) = single_pipeline(new_pipeline().add(QuickExitMiddleware).build());
let test_router = build_simple_router(|route| {
route.get("/").to(test_handler);
});
let router = build_router(chain, pipelines, |route| {
route.delegate("/test").to_router(test_router);
});
let test_server = TestServer::new(router).unwrap();
let response = test_server
.client()
.get("http://localhost/test/")
.perform()
.unwrap();
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
#[test]
fn delegate_without_pipelines_skips_pipelines() {
let (chain, pipelines) = single_pipeline(new_pipeline().add(QuickExitMiddleware).build());
let test_router = build_simple_router(|route| {
route.get("/").to(test_handler);
});
let router = build_router(chain, pipelines, |route| {
route
.delegate_without_pipelines("/test")
.to_router(test_router);
});
let test_server = TestServer::new(router).unwrap();
let response = test_server
.client()
.get("http://localhost/test/")
.perform()
.unwrap();
assert_eq!(response.status(), StatusCode::ACCEPTED);
}
}