如何在 warp 中重用路径?
How do I reuse paths in warp?
我想要一个带有 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 warp 的范围?
假设我的解释是正确的,您想重用路径,这样如果要更改 "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 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 warp 的范围?
假设我的解释是正确的,您想重用路径,这样如果要更改 "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);