我想要一个带有 Rust warp 的分层路由结构,如下所示:
/
/api
/api/public
/api/public/articles
/api/admin
/api/admin/articles
我想像下面的代码一样定义我的路由范围,当然,它不起作用:
// *** 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
}
有什么方法可以实现搭载路线,即具有 rust 迹扭曲的范围吗?
最佳答案
假设我的解释正确,您希望重用路径,这样如果要更改 "api"
,您只需在一处执行此操作。
如果是这样,那么是的,您几乎可以完全按照您的想象去做。您只需将 warp::path("...")
分配给一个变量,然后就可以将它重用于 map()
和 and()
像这样:
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);
关于rust - 如何重用扭曲中的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65490367/