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
#![macro_use] use core::{Request, Response}; use std::sync::Arc; use futures::future::{Future, IntoFuture}; type MiddleWareFuture<I> = Box<Future<Item = I, Error = Response>>; /// The middleware Trait. /// In arc-reactor the middleware system is designed to be as intuitive and as simple as possible. /// /// # How it works. /// /// Think of a `MiddleWare<T>` as a function that returns `Result<T, Response>` /// /// E.g A middleware is given a `Request` to do some processing, if that MiddleWare, returns Ok(request). /// Then the returned request is passed to the next middleware or route handler. /// /// ```rust,ignore /// use arc_reactor::prelude::*; /// /// #[middleware(Request)] /// fn hasAccessToken(req: Request) { /// if let Some(user) = req.query::AccessToken().and_then(|token| /// await!(db::fetchUserFromToken(token)).ok() // psuedo-code this won't compile, /// // the await macro is exported in the prelude. it is re-exported from futures_await /// ) /// req.set::<User>(user); /// return Ok(req); /// } /// let res = Response::new().with_status(StatusCode::Unauthorized); /// return Err(res) /// } /// /// /// #[service] /// fn UserService(req: Request, res: Response) { /// let user = req.get::<User>().unwrap(); // It's safe to unwrap here, because the service is only called when `hasAccessToken` returns Ok(request). /// .... /// } /// /// /// fn main() { /// let router = Router::new() /// .get("/user", arc!(mw![hasAccessToken], UserService)); /// ..... /// // start the server mount the routes. /// /// } /// ``` /// /// ## Working With a `Vec<MiddleWare<T>>` /// /// The same rules as above applies, each middleware pass the request among themselves to do processing. If any of them returns `Err(Response)`, the rest of the middlewares are skipped as well as the route handler. /// /// /// ```rust,ignore /// use arc_reactor::prelude::*; /// /// #[middleware(Request)] /// fn middleware1(req: Request) { /// println!("will be executed"); /// return Ok(req) /// } /// /// #[middleware(Request)] /// fn middleware2(req: Request) { /// println!("will always be called, because middleware1 always returns Ok(request)"); /// return Err(Response::new().with_status(StatusCode::Unauthorized)) /// } /// /// #[middleware(Request)] /// fn middleware3(req: Request) { /// println!("will never be called"); /// return Ok(req) /// } /// /// #[service] /// fn TestService(req: Request, res: Response) { /// println!("Will never be called, because middleware 2 returns an Err(response)") /// ...... /// } /// /// /// fn main() { /// let router = Router::new() /// .get("/user", arc!(mw![middleware1, middleware2, middleware3], TestService)); // note that the order of middlewares matter! /// ..... /// // start the server mount the routes. /// /// } /// /// ``` /// /// # Note /// Please note that you would probably never have a reason to implement this trait on your type directly. /// /// Instead you'll use the middleware proc_macro [`#[middleware]`](../impl_service/fn.middleware.html) to decorate your functions. /// The proc_macro makes `MiddleWare`'s aasynchronous by default. so you can `await!()` on futures. pub trait MiddleWare<T>: Sync + Send { fn call(&self, param: T) -> MiddleWareFuture<T>; } /// This enables an vector of `MiddleWare<Request>` to behave like a single `MiddleWare<Request>` /// returning `Err(Response)` in any of the `MiddleWare<Request>` will cause the rest of the middlewares to be skipped. /// Note that there's a conveinience macro `mw` that allows you not write boxes everywhere. /// impl MiddleWare<Request> for Vec<Arc<Box<MiddleWare<Request>>>> { fn call(&self, request: Request) -> MiddleWareFuture<Request> { self .iter() .fold(box Ok(request).into_future(), |request, middleware| { let clone = middleware.clone(); box request.and_then(move |req| clone.call(req)) }) } } /// This enables an vector of `MiddleWare<Request>` to behave like a single `MiddleWare<Request>` /// returning `Err(Response)` in any of the `MiddleWare<Request>` will cause the rest of the middlewares to be skipped. /// Note that there's a conveinience macro `mw` that allows you not write boxes everywhere. /// impl MiddleWare<Response> for Vec<Arc<Box<MiddleWare<Response>>>> { fn call(&self, response: Response) -> MiddleWareFuture<Response> { self .iter() .fold(box Ok(response).into_future(), |response, middleware| { let clone = middleware.clone(); box response.and_then(move |res| clone.call(res)) }) } } #[macro_export] macro_rules! mw { ($($middlewares:expr), +) => {{ use std::sync::Arc; let middleWares: Vec<Arc<Box<MiddleWare<_>>>> = vec![$(Arc::new(box $middlewares)), +]; box middleWares as Box<MiddleWare<_>> }}; }