Skip to content

Commit eb7faf8

Browse files
committed
Allow using Option<Middleware> to enable/disable a middleware
Currently, there is `Condition`, which accepts a boolean (to enable/disable) and an instance to the actual middleware. The downside of that is, that such a middleware needs to be constructed in any case. Even if the middleware is used or not. However, the middleware is not used when it is disabled. Only the type seems required. So this PR adds a `from_option` function, which allows passing in an `Option` instead of boolean and instance. If the option "is some" it is enabled. Otherwise, not.
1 parent dce57a7 commit eb7faf8

File tree

1 file changed

+61
-6
lines changed

1 file changed

+61
-6
lines changed

actix-web/src/middleware/condition.rs

+61-6
Original file line numberDiff line numberDiff line change
@@ -26,18 +26,31 @@ use crate::{
2626
/// let app = App::new()
2727
/// .wrap(Condition::new(enable_normalize, NormalizePath::default()));
2828
/// ```
29+
/// Or you can use an `Option` to create a new instance:
30+
/// ```
31+
/// use actix_web::middleware::{Condition, NormalizePath};
32+
/// use actix_web::App;
33+
///
34+
/// let app = App::new()
35+
/// .wrap(Condition::from_option(Some(NormalizePath::default())));
36+
/// ```
2937
pub struct Condition<T> {
30-
transformer: T,
31-
enable: bool,
38+
transformer: Option<T>,
3239
}
3340

3441
impl<T> Condition<T> {
3542
pub fn new(enable: bool, transformer: T) -> Self {
3643
Self {
37-
transformer,
38-
enable,
44+
transformer: match enable {
45+
true => Some(transformer),
46+
false => None,
47+
},
3948
}
4049
}
50+
51+
pub fn from_option(transformer: Option<T>) -> Self {
52+
Self { transformer }
53+
}
4154
}
4255

4356
impl<S, T, Req, BE, BD, Err> Transform<S, Req> for Condition<T>
@@ -55,8 +68,8 @@ where
5568
type Future = LocalBoxFuture<'static, Result<Self::Transform, Self::InitError>>;
5669

5770
fn new_transform(&self, service: S) -> Self::Future {
58-
if self.enable {
59-
let fut = self.transformer.new_transform(service);
71+
if let Some(transformer) = &self.transformer {
72+
let fut = transformer.new_transform(service);
6073
async move {
6174
let wrapped_svc = fut.await?;
6275
Ok(ConditionMiddleware::Enable(wrapped_svc))
@@ -131,6 +144,7 @@ where
131144
#[cfg(test)]
132145
mod tests {
133146
use actix_service::IntoService as _;
147+
use futures_util::future::ok;
134148

135149
use super::*;
136150
use crate::{
@@ -167,6 +181,18 @@ mod tests {
167181
let _ = Condition::new(true, middleware::ErrorHandlers::<Bytes>::new());
168182
}
169183

184+
fn create_optional_mw<B>(enabled: bool) -> Option<ErrorHandlers<B>>
185+
where
186+
B: 'static,
187+
{
188+
match enabled {
189+
true => Some(
190+
ErrorHandlers::new().handler(StatusCode::INTERNAL_SERVER_ERROR, render_500),
191+
),
192+
false => None,
193+
}
194+
}
195+
170196
#[actix_rt::test]
171197
async fn test_handler_enabled() {
172198
let srv = |req: ServiceRequest| async move {
@@ -204,4 +230,33 @@ mod tests {
204230
test::call_service(&mw, TestRequest::default().to_srv_request()).await;
205231
assert_eq!(resp.headers().get(CONTENT_TYPE), None);
206232
}
233+
234+
#[actix_rt::test]
235+
async fn test_handler_some() {
236+
let srv = |req: ServiceRequest| {
237+
ok(req.into_response(HttpResponse::InternalServerError().finish()))
238+
};
239+
240+
let mw = Condition::from_option(create_optional_mw(true))
241+
.new_transform(srv.into_service())
242+
.await
243+
.unwrap();
244+
let resp = test::call_service(&mw, TestRequest::default().to_srv_request()).await;
245+
assert_eq!(resp.headers().get(CONTENT_TYPE).unwrap(), "0001");
246+
}
247+
248+
#[actix_rt::test]
249+
async fn test_handler_none() {
250+
let srv = |req: ServiceRequest| {
251+
ok(req.into_response(HttpResponse::InternalServerError().finish()))
252+
};
253+
254+
let mw = Condition::from_option(create_optional_mw(false))
255+
.new_transform(srv.into_service())
256+
.await
257+
.unwrap();
258+
259+
let resp = test::call_service(&mw, TestRequest::default().to_srv_request()).await;
260+
assert_eq!(resp.headers().get(CONTENT_TYPE), None);
261+
}
207262
}

0 commit comments

Comments
 (0)