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
//! Defines types that support individual application routes.
//!
//! The Gotham `Router` having identified `1..n` potential `Route` instances to service a
//! request via route `Tree` traversal will attempt to identify a matching `Route` instance and
//! dispatch to it when it does so.

pub mod matcher;
pub mod dispatch;

use std::marker::PhantomData;

use hyper::{Request, Response};
use hyper::StatusCode;

use router::route::dispatch::Dispatcher;
use handler::HandlerFuture;
use router::request::query_string::QueryStringExtractor;
use router::route::matcher::RouteMatcher;
use router::tree::SegmentMapping;
use router::request::path::PathExtractor;
use state::State;

#[derive(Clone, Copy, PartialEq)]
/// Indicates how this Route behaves in relation to external `Router` instances.
pub enum Delegation {
    /// Invokes a `Handler` that is considered 'internal' to the current `Router`+`Route` instance,
    /// this is generally true of all application implemented handlers.
    Internal,

    /// Invokes an external `Router` as the `Handler` for `Requests` matched by this `Route`. This is
    /// useful when supporting "Modular Applications". The external `Router` will not have access to
    /// any `Request` path segments processed in order to arrive at the current `Route`.
    External,
}

/// A type that determines if its associated logic can be exposed by the `Router`
/// in response to an external request. If it determines that it can the `Route` runs extractors on
/// the `Request`, potentially extending `State` before dispatching to the `Dispatcher` assigned
/// to this `Route`.
///
/// Capable of delegating requests to secondary `Router` instances in order to support "Modular
/// Applications".
pub trait Route {
    /// Determines if this `Route` can be invoked, based on the `Request`.
    fn is_match(&self, state: &State, req: &Request) -> Result<(), StatusCode>;

    /// Determines if this `Route` intends to delegate requests to a secondary `Router` instance.
    fn delegation(&self) -> Delegation;

    /// Extracts the `Request` path and stores it in `State`
    fn extract_request_path(
        &self,
        state: &mut State,
        segment_mapping: SegmentMapping,
    ) -> Result<(), String>;

    /// Extends the `Response` object when path extraction fails
    fn extend_response_on_path_error(&self, state: &mut State, res: &mut Response);

    /// Extracts the `Request` query string and stores it in `State`
    fn extract_query_string(&self, state: &mut State, query: Option<&str>) -> Result<(), String>;

    /// Extends the `Response` object when query string extraction fails
    fn extend_response_on_query_string_error(&self, state: &mut State, res: &mut Response);

    /// Final call made by the `Router` to the matched `Route` allowing
    /// application specific logic to respond to the request.
    fn dispatch(&self, state: State, req: Request) -> Box<HandlerFuture>;
}

/// Default implementation for `Route`.
///
/// # Examples
///
/// ## Standard `Route` which calls application code
///
/// ```rust
/// # extern crate gotham;
/// # extern crate hyper;
/// #
/// # use hyper::{Request, Response, Method, StatusCode};
/// #
/// # use gotham::http::response::create_response;
/// # use gotham::router::request::path::NoopPathExtractor;
/// # use gotham::router::request::query_string::NoopQueryStringExtractor;
/// # use gotham::router::route::matcher::MethodOnlyRouteMatcher;
/// # use gotham::router::route::dispatch::{new_pipeline_set, finalize_pipeline_set, DispatcherImpl};
/// # use gotham::state::State;
/// # use gotham::router::route::{RouteImpl, Extractors, Delegation};
/// #
/// # fn main() {
///   fn handler(state: State, _req: Request) -> (State, Response) {
///     let res = create_response(&state, StatusCode::Ok, None);
///     (state, res)
///   }
///
///   let pipeline_set = finalize_pipeline_set(new_pipeline_set());
///   let methods = vec![Method::Get];
///   let matcher = MethodOnlyRouteMatcher::new(methods);
///   let dispatcher = Box::new(DispatcherImpl::new(|| Ok(handler), (), pipeline_set));
///   let extractors: Extractors<NoopPathExtractor, NoopQueryStringExtractor> = Extractors::new();
///   RouteImpl::new(matcher, dispatcher, extractors, Delegation::Internal);
/// # }
/// ```
///
/// ## A `Route` which delegates remaining `Request` details to a secondary `Router` instance
///
/// ```rust
/// # extern crate gotham;
/// # extern crate hyper;
/// #
/// # use hyper::{Request, Response, StatusCode, Method};
/// #
/// # use gotham::http::response::create_response;
/// # use gotham::router::request::path::NoopPathExtractor;
/// # use gotham::router::request::query_string::NoopQueryStringExtractor;
/// # use gotham::router::route::matcher::MethodOnlyRouteMatcher;
/// # use gotham::router::route::dispatch::{new_pipeline_set, finalize_pipeline_set, DispatcherImpl};
/// # use gotham::state::State;
/// # use gotham::router::Router;
/// # use gotham::router::route::{RouteImpl, Extractors, Delegation};
/// # use gotham::router::tree::TreeBuilder;
/// # use gotham::router::response::finalizer::ResponseFinalizerBuilder;
/// #
/// # fn main() {
///   fn handler(state: State, _req: Request) -> (State, Response) {
///     let res = create_response(&state, StatusCode::Ok, None);
///     (state, res)
///   }
///
///   let secondary_router = {
///        let pipeline_set = finalize_pipeline_set(new_pipeline_set());
///        let mut tree_builder = TreeBuilder::new();
///
///        let route = {
///            let methods = vec![Method::Get];
///            let matcher = MethodOnlyRouteMatcher::new(methods);
///            let dispatcher = Box::new(DispatcherImpl::new(|| Ok(handler), (), pipeline_set));
///            let extractors: Extractors<NoopPathExtractor,
///                                       NoopQueryStringExtractor> = Extractors::new();
///            let route = RouteImpl::new(matcher, dispatcher, extractors, Delegation::Internal);
///            Box::new(route)
///        };
///        tree_builder.add_route(route);
///
///        let tree = tree_builder.finalize();
///        Router::new(tree, ResponseFinalizerBuilder::new().finalize())
///   };
///
///   let pipeline_set = finalize_pipeline_set(new_pipeline_set());
///   let methods = vec![Method::Get];
///   let matcher = MethodOnlyRouteMatcher::new(methods);
///   let dispatcher = Box::new(DispatcherImpl::new(secondary_router, (), pipeline_set));
///   let extractors: Extractors<NoopPathExtractor, NoopQueryStringExtractor> = Extractors::new();
///   RouteImpl::new(matcher, dispatcher, extractors, Delegation::External);
/// # }
/// ```
pub struct RouteImpl<RM, RE, QSE>
where
    RM: RouteMatcher,
    RE: PathExtractor,
    QSE: QueryStringExtractor,
{
    matcher: RM,
    dispatcher: Box<Dispatcher + Send + Sync>,
    _extractors: Extractors<RE, QSE>,
    delegation: Delegation,
}

/// Extractors used by `RouteImpl` to acquire request data and change into a type safe form
/// for use by custom `Middleware` and `Handler` implementations.
pub struct Extractors<RE, QSE>
where
    RE: PathExtractor,
    QSE: QueryStringExtractor,
{
    rpe_phantom: PhantomData<RE>,
    qse_phantom: PhantomData<QSE>,
}

impl<RM, RE, QSE> RouteImpl<RM, RE, QSE>
where
    RM: RouteMatcher,
    RE: PathExtractor,
    QSE: QueryStringExtractor,
{
    /// Creates a new `RouteImpl`
    pub fn new(
        matcher: RM,
        dispatcher: Box<Dispatcher + Send + Sync>,
        _extractors: Extractors<RE, QSE>,
        delegation: Delegation,
    ) -> Self {
        RouteImpl {
            matcher,
            dispatcher,
            _extractors,
            delegation,
        }
    }
}

impl<RE, QSE> Extractors<RE, QSE>
where
    RE: PathExtractor,
    QSE: QueryStringExtractor,
{
    /// Creates a new set of Extractors for use with a `RouteImpl`
    pub fn new() -> Self {
        Extractors {
            rpe_phantom: PhantomData,
            qse_phantom: PhantomData,
        }
    }
}

impl<RM, RE, QSE> Route for RouteImpl<RM, RE, QSE>
where
    RM: RouteMatcher,
    RE: PathExtractor,
    QSE: QueryStringExtractor,
{
    fn is_match(&self, state: &State, req: &Request) -> Result<(), StatusCode> {
        self.matcher.is_match(state, req)
    }

    fn delegation(&self) -> Delegation {
        self.delegation
    }

    fn dispatch(&self, state: State, req: Request) -> Box<HandlerFuture> {
        self.dispatcher.dispatch(state, req)
    }

    fn extract_request_path(
        &self,
        state: &mut State,
        segment_mapping: SegmentMapping,
    ) -> Result<(), String> {
        RE::extract(state, segment_mapping)
    }

    fn extend_response_on_path_error(&self, state: &mut State, res: &mut Response) {
        RE::extend(state, res)
    }

    fn extract_query_string(&self, state: &mut State, query: Option<&str>) -> Result<(), String> {
        QSE::extract(state, query)
    }

    fn extend_response_on_query_string_error(&self, state: &mut State, res: &mut Response) {
        QSE::extend(state, res)
    }
}