Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions actix-web/src/middleware/condition_option.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
//! For middleware documentation, see [`ConditionOption`].

use futures_core::future::LocalBoxFuture;
use futures_util::future::FutureExt as _;

use crate::{
body::EitherBody,
dev::{Service, ServiceResponse, Transform},
middleware::condition::ConditionMiddleware,
};

/// Middleware for conditionally enabling other middleware in an [`Option`].
///
/// Uses [`Condition`](crate::middleware::condition::Condition) under the hood.
///
/// # Example
/// ```
/// use actix_web::middleware::{ConditionOption, NormalizePath};
/// use actix_web::App;
///
/// let normalize: ConditionOption<_> = Some(NormalizePath::default()).into();
/// let app = App::new()
/// .wrap(normalize);
/// ```
pub struct ConditionOption<T>(Option<T>);

impl<T> From<Option<T>> for ConditionOption<T> {
fn from(value: Option<T>) -> Self {
Self(value)
}
}

impl<S, T, Req, BE, BD, Err> Transform<S, Req> for ConditionOption<T>
where
S: Service<Req, Response = ServiceResponse<BD>, Error = Err> + 'static,
T: Transform<S, Req, Response = ServiceResponse<BE>, Error = Err>,
T::Future: 'static,
T::InitError: 'static,
T::Transform: 'static,
{
type Response = ServiceResponse<EitherBody<BE, BD>>;
type Error = Err;
type Transform = ConditionMiddleware<T::Transform, S>;
type InitError = T::InitError;
type Future = LocalBoxFuture<'static, Result<Self::Transform, Self::InitError>>;

fn new_transform(&self, service: S) -> Self::Future {
match &self.0 {
Some(transformer) => {
let fut = transformer.new_transform(service);
async move {
let wrapped_svc = fut.await?;
Ok(ConditionMiddleware::Enable(wrapped_svc))
}
.boxed_local()
}
None => async move { Ok(ConditionMiddleware::Disable(service)) }.boxed_local(),
}
}
}
2 changes: 2 additions & 0 deletions actix-web/src/middleware/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

mod compat;
mod condition;
mod condition_option;
mod default_headers;
mod err_handlers;
mod logger;
Expand All @@ -11,6 +12,7 @@ mod normalize;

pub use self::compat::Compat;
pub use self::condition::Condition;
pub use self::condition_option::ConditionOption;
pub use self::default_headers::DefaultHeaders;
pub use self::err_handlers::{ErrorHandlerResponse, ErrorHandlers};
pub use self::logger::Logger;
Expand Down