Function axum_extra::middleware::option_layer

source ·
pub fn option_layer<L>(layer: Option<L>) -> Either<L, Identity>
Expand description

Convert an Option<Layer> into a Layer.

If the layer is a Some it’ll be applied, otherwise not.

§Example

use axum_extra::middleware::option_layer;
use axum::{Router, routing::get};
use std::time::Duration;
use tower_http::timeout::TimeoutLayer;

let timeout_layer = option_timeout.map(TimeoutLayer::new);

let app = Router::new()
    .route("/", get(|| async {}))
    .layer(option_layer(timeout_layer));

§Difference between this and tower::util::option_layer

tower::util::option_layer always changes the error type to BoxError which requires using HandleErrorLayer when used with axum, even if the layer you’re applying uses Infallible.

axum_extra::middleware::option_layer on the other hand doesn’t change the error type so can be applied directly.