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
//! Defines types for Gotham middleware

use std::io;
use hyper::Request;

use handler::HandlerFuture;
use state::State;

pub mod pipeline;
pub mod session;

/// `Middleware` has the opportunity to provide additional behaviour to the `Request` / `Response`
/// interaction. Middleware-specific state data can be recorded in the `State` struct for
/// use elsewhere.
///
/// # Examples
///
/// Taking no action, and immediately passing the `Request` through to the rest of the application:
///
/// ```rust,no_run
/// # extern crate gotham;
/// # extern crate hyper;
/// #
/// # use gotham::handler::HandlerFuture;
/// # use gotham::middleware::Middleware;
/// # use gotham::state::State;
/// # use hyper::Request;
/// #
/// struct NoopMiddleware;
///
/// impl Middleware for NoopMiddleware {
///     fn call<Chain>(self, state: State, req: Request, chain: Chain) -> Box<HandlerFuture>
///         where Chain: FnOnce(State, Request) -> Box<HandlerFuture> + Send + 'static
///     {
///         chain(state, req)
///     }
/// }
/// #
/// # fn main() {
/// #  NoopMiddleware {};
/// # }
/// ```
///
/// Recording a piece of state data before passing the request through:
///
/// ```rust,no_run
/// # extern crate gotham;
/// # #[macro_use]
/// # extern crate gotham_derive;
/// # extern crate hyper;
/// #
/// # use gotham::handler::HandlerFuture;
/// # use gotham::middleware::Middleware;
/// # use gotham::state::State;
/// # use hyper::Request;
/// #
/// struct MiddlewareWithStateData;
///
/// # #[allow(unused)]
/// # #[derive(StateData)]
/// struct MiddlewareStateData {
///     i: i32,
/// }
///
/// impl Middleware for MiddlewareWithStateData {
///     fn call<Chain>(self, mut state: State, req: Request, chain: Chain) -> Box<HandlerFuture>
///         where Chain: FnOnce(State, Request) -> Box<HandlerFuture> + Send + 'static
///     {
///         state.put(MiddlewareStateData { i: 10 });
///         chain(state, req)
///     }
/// }
/// #
/// # fn main() {
/// #     MiddlewareWithStateData {};
/// # }
/// ```
///
/// Terminating the request early based on some arbitrary condition:
///
/// ```rust,no_run
/// # extern crate gotham;
/// # extern crate hyper;
/// # extern crate futures;
/// #
/// # use gotham::http::response::create_response;
/// # use gotham::handler::HandlerFuture;
/// # use gotham::middleware::Middleware;
/// # use gotham::state::{State};
/// # use hyper::Request;
/// # use hyper::{Method, StatusCode};
/// # use futures::{future, Future};
/// #
/// struct ConditionalMiddleware;
///
/// impl Middleware for ConditionalMiddleware {
///     fn call<Chain>(self, state: State, req: Request, chain: Chain) -> Box<HandlerFuture>
///         where Chain: FnOnce(State, Request) -> Box<HandlerFuture> + Send + 'static
///     {
///         if *req.method() == Method::Get {
///             chain(state, req)
///         } else {
///             let response = create_response(&state, StatusCode::MethodNotAllowed, None);
///             future::ok((state, response)).boxed()
///         }
///     }
/// }
/// #
/// # fn main() {
/// #     ConditionalMiddleware {};
/// # }
/// ```
///
/// Asynchronous middleware, which continues the request after some action completes:
///
/// ```rust,no_run
/// # extern crate gotham;
/// # extern crate hyper;
/// # extern crate futures;
/// #
/// # use gotham::handler::HandlerFuture;
/// # use gotham::middleware::Middleware;
/// # use gotham::state::State;
/// # use hyper::Request;
/// # use futures::{future, Future};
/// #
/// struct AsyncMiddleware;
///
/// impl Middleware for AsyncMiddleware {
///     fn call<Chain>(self, state: State, req: Request, chain: Chain) -> Box<HandlerFuture>
///         where Chain: FnOnce(State, Request) -> Box<HandlerFuture> + Send + 'static
///     {
///         // This could be any asynchronous action. `future::lazy(_)` defers a function
///         // until the next cycle of tokio's event loop.
///         let f = future::lazy(|| future::ok(()));
///         f.and_then(move |_| chain(state, req)).boxed()
///     }
/// }
/// #
/// # fn main() {
/// #    AsyncMiddleware {};
/// # }
/// ```
pub trait Middleware {
    /// Entry point to the middleware. To pass the request on to the application, the middleware
    /// invokes the `chain` function with the provided `state` and `request`.
    ///
    /// By convention, the middleware should:
    ///
    /// * Avoid modifying the `Request`, unless it is already determined that the response will be
    ///   generated by the middleware (i.e. without calling `chain`);
    /// * Ensure to pass the same `State` to `chain`, rather than creating a new `State`.
    fn call<Chain>(self, state: State, request: Request, chain: Chain) -> Box<HandlerFuture>
    where
        Chain: FnOnce(State, Request) -> Box<HandlerFuture> + Send + 'static,
        Self: Sized;
}

/// Creates new `Middleware` values.
pub trait NewMiddleware: Sync {
    /// The type of `Middleware` created by the implementor.
    type Instance: Middleware;

    /// Create and return a new `Middleware` value.
    fn new_middleware(&self) -> io::Result<Self::Instance>;
}