From 54475a57e8432c22e8e209e3da5de0336672f2e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=CE=BAeen?= <3han5chou7@gmail.com> Date: Tue, 26 Nov 2019 04:10:29 +0900 Subject: [PATCH] support IntoTransform middlewares --- src/middleware/condition.rs | 50 +++++++++++++++++++++++++++++++++---- 1 file changed, 45 insertions(+), 5 deletions(-) diff --git a/src/middleware/condition.rs b/src/middleware/condition.rs index ddc5fdd42..e198a546b 100644 --- a/src/middleware/condition.rs +++ b/src/middleware/condition.rs @@ -1,9 +1,11 @@ //! `Middleware` for conditionally enables another middleware. -use actix_service::{Service, Transform}; +use actix_service::{IntoTransform, Service, Transform}; use futures::future::{ok, Either, FutureResult, Map}; use futures::{Future, Poll}; +use std::marker::PhantomData; /// `Middleware` for conditionally enables another middleware. +/// /// The controled middleware must not change the `Service` interfaces. /// This means you cannot control such middlewares like `Logger` or `Compress`. /// @@ -16,17 +18,55 @@ use futures::{Future, Poll}; /// fn main() { /// let enable_normalize = std::env::var("NORMALIZE_PATH") == Ok("true".into()); /// let app = App::new() -/// .wrap(Condition::new(enable_normalize, NormalizePath)); +/// .wrap(Condition::enable_if(enable_normalize, NormalizePath)); /// } /// ``` -pub struct Condition { +pub struct Condition { trans: T, enable: bool, + _phantom: PhantomData, } -impl Condition { +#[doc(hidden)] +pub enum No {} +#[doc(hidden)] +pub enum Yes {} + +impl Condition { + /// Conditionally enables another middleware. + pub fn enable_if(enable: bool, trans: T) -> Self { + Self { + trans, + enable, + _phantom: PhantomData, + } + } +} + +impl Condition { + /// Create a new condition middleware. + /// This function is not recommended in favor of [`enable_if`](#method.enable_if). pub fn new(enable: bool, trans: T) -> Self { - Self { trans, enable } + Self { + trans, + enable, + _phantom: PhantomData, + } + } +} + +impl IntoTransform, S> for Condition +where + S: Service, + T: IntoTransform, + Target: Transform, +{ + fn into_transform(self) -> Condition { + Condition { + enable: self.enable, + trans: self.trans.into_transform(), + _phantom: PhantomData, + } } }