rustrust-warp

How can I conditionally disable api routes in warp?


I am new to Rust and Warp and I am trying to make routes available conditionally. For example, I have a route /leaves, and based upon the flag I need to process this request or send an error response.

let enable_api = true // some config part

let leaves_filter = warp::path("leaves")
    .and(store_filter)
    .and(warp::path::param())
    .and(warp::path::param())
    .and_then(handler::handle_leaves)
    .boxed();

let routes = (info_filter).or(leaves_filter).boxed(); 

I tried to pass the flag to handler::handle_leaves and added a validation check to return a conditional response. But I want to know if we can filter the request before calling the handler.

What should be the good way to handle this?


Solution

  • Taking tips from Issue #21: How to execute a filter conditionally? You will need to add a filter that can reject immediately if the flag is missing. So something like this:

    let enable_api = true;
    
    let leaves_filter = warp::path("leaves")
        .and_then(move || if enable_api { Ok(()) } else { Err(warp::reject::not_found()} })
        .and(store_filter)
        .and(warp::path::param())
        .and(warp::path::param())
        .and_then(|_, store, param1, param2| handler::handle_leaves(store, param1, param2));
    
    let routes = info_filter.or(leaves_filter);