I'm trying to refactor my REST server to use modules. I am having a lot of trouble determining what types to return. Consider the simple example below:
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!"))
}
}
This does not compile because the return type does not match what is 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>`
I've tried a number of things. The first thing I thought was the following:
pub mod routers {
use warp::Filter;
pub fn get_routes() -> impl Filter {
warp::any().map(|| "Hello, World!")
}
}
But I get this compile error:
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`
I'm really confused about how to make this work. Clearly, I am still confused by Rust's generics and traits.
An easy way is to use impl Filter
with some tweaks:
use warp::{Filter, Rejection, Reply};
fn get_routes() -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {
warp::any().map(|| "Hello, World!")
}