I'd like to have a hierarchical route structure with Rust warp like this:
/
/api
/api/public
/api/public/articles
/api/admin
/api/admin/articles
I'd like to define my route scopes like in the following code, which is – of course – not working:
// *** Again: this code does NOT work.
// *** I've put it here simply for demonstration purposes
pub fn get_routes() -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone {
let articles = warp::path("articles")
.map(|| "articles index");
let public = warp::path("public")
.and(warp::path::end())
.map(|| "public index")
.or(articles);
let admin = warp::path("admin")
.and(warp::path::end())
.map(|| "admin index")
.or(articles);
let api = warp::path("api")
.and(warp::path::end())
.map(|| "api index")
.or(admin);
let root_index = warp::path::end()
.map(|| "root index")
.or(api);
root_index
}
Is there any way I can achieve piggybacking routes i.e. scopes with rust warp?
Assuming I'm interpreting it correctly, you want to reuse paths, such that if "api"
were to be changed, you'd only have to do so in one place.
If so, then yes you can almost do exactly what you're picturing. You just need to assign your warp::path("...")
to a variable, and then you can reuse it for both map()
and and()
like so:
use warp::path::end;
let articles = warp::path("articles")
.and(end())
.map(|| "articles index");
let public = warp::path("public");
let public = public
.and(end())
.map(|| "public index")
.or(public.and(articles));
let admin = warp::path("admin");
let admin = admin
.and(end())
.map(|| "admin index")
.or(admin.and(articles));
let api = warp::path("api");
let api = api
.and(end())
.map(|| "api index")
.or(api.and(admin))
.or(api.and(public));
let root_index = end()
.map(|| "root index")
.or(api);