realaravinth / actix-optional-middleware

Conditionally load actix-web middleware

Home Page:https://realaravinth.github.io/actix-optional-middleware/actix_optional_middleware/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Actix Optional Middleware

Conditionally load middleware

Documentation CI (Linux) dependency status

codecov

This library supports conditional loading of an Actix Web middleware. When conditions are not met, a dummy middleware that simply forwards requests are substituted.

Usage

Add this to your Cargo.toml:

actix-optional-middleware = { version = "0.1", git = "https://github.com/realaravinth/actix-optional-middleware" }

Example

use std::rc::Rc;

use actix_optional_middleware::{Group, Dummy};
use actix_web::dev::{AnyBody, Service, ServiceRequest,
ServiceResponse, Transform};
use actix_web::middleware::DefaultHeaders;
use actix_web::{web, App, Error, HttpServer, Responder, get};

#[get("/test", wrap = "get_group_middleware()")]
async fn h1() -> impl Responder {
    "Handler 1"
}

// flip this value to see dummy in action
const ACTIVE: bool = true;

fn get_group_middleware<S>() -> Group<Dummy, DefaultHeaders, S>
where
    S: Service<ServiceRequest, Response = ServiceResponse<AnyBody>, Error = Error>
		+ 'static,
{
    if ACTIVE {
        Group::Real(Rc::new(DefaultHeaders::new()
               .header("Permissions-Policy", "interest-cohort=()"
        )))
    } else {
        Group::default()
    }
}

About

Conditionally load actix-web middleware

https://realaravinth.github.io/actix-optional-middleware/actix_optional_middleware/

License:Apache License 2.0


Languages

Language:Rust 100.0%