rust - 如何重用扭曲中的路径?

标签 rust rust-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 迹扭曲的范围吗?

最佳答案

假设我的解释正确,您希望重用路径,这样如果要更改 "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/

相关文章:

Vec : compilation error when using the val0 method 中的 Rust 元组

rust - 我必须将我的闭包装箱以将其保存为结构中的字段吗?

json - 东京和塞尔德 : deserializing JSON

rust - 我如何使字符串比闭包体生命周期更长?

rust - 从函数返回扭曲过滤器

rust - 有没有办法在 Warp 中作为过滤器的一部分进行验证?

rust - 如何使用 Warp 检查授权 header ?

enums - 为什么使一个枚举变体成为 `f64` 会增加此枚举的大小?

thread-safety - 我如何保证一个没有实现 Sync 的类型实际上可以在线程之间安全地共享?

rust - 如果外部包装箱明确要求静态生命周期,该怎么办?