如何使用 warp 创建到 return 路由的函数

How to create function to return routes with warp

我正在尝试重构我的 REST 服务器以使用模块。我在确定 return 的类型时遇到了很多麻烦。考虑下面的简单示例:

main.rs

use warp_server::routes::routers::get_routes;

#[tokio::main]
async fn main() {
    let routes = get_routes();
    warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
}

routes.rs

pub mod routers {
    use warp::Filter;

    pub fn get_routes() -> Box<dyn Filter> {
        Box::new(warp::any().map(|| "Hello, World!"))
    }
}

这不会编译,因为 return 类型与 returned 不匹配。

error[E0191]: the value of the associated types `Error` (from trait `warp::filter::FilterBase`), `Extract` (from trait `warp::filter::FilterBase`), `Future` (from trait `warp::filter::FilterBase`) must be specified
 --> src/routes.rs:4:36
  |
4 |     pub fn get_routes() -> Box<dyn Filter> {
  |                                    ^^^^^^ help: specify the associated types: `Filter<Extract = Type, Error = Type, Future = Type>`

我已经尝试了很多东西。我首先想到的是:

pub mod routers {
    use warp::Filter;

    pub fn get_routes() -> impl Filter {
        warp::any().map(|| "Hello, World!")
    }
}

但是我得到这个编译错误:

error[E0277]: the trait bound `impl warp::Filter: Clone` is not satisfied
  --> src/main.rs:6:17
   |
6  |     warp::serve(routes).run(([127, 0, 0, 1], 3030)).await;
   |                 ^^^^^^ the trait `Clone` is not implemented for `impl warp::Filter`
   | 
  ::: /Users/stephen.gibson/.cargo/registry/src/github.com-1ecc6299db9ec823/warp-0.3.1/src/server.rs:25:17
   |
25 |     F: Filter + Clone + Send + Sync + 'static,
   |                 ----- required by this bound in `serve`

我真的很困惑如何完成这项工作。显然,我仍然对 Rust 的泛型和特征感到困惑。

一种简单的方法是使用 impl Filter 并进行一些调整:

use warp::{Filter, Rejection, Reply};

fn get_routes() -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {
    warp::any().map(|| "Hello, World!")
}