1

这是新手入门的锈变形示例。它应该是“超级简单”,但它现在让我觉得超级愚蠢。

use warp::Filter;

#[tokio::main]
async fn main() {
    // GET /hello/warp => 200 OK with body "Hello, warp!"
    let hello = warp::path!("hello" / String)
        .map(|name| format!("Hello, {}!", name));

    warp::serve(hello)
        .run(([127, 0, 0, 1], 3030))
        .await;
}

我想在根路径上运行它,定义如下:

let hello = warp::path!("" /).map(|| "Hello!");

但宏不采用空路径名。我得到错误:

no rules expected the token `start`

我想“超级容易”对不同的人意味着不同的事情。

附录:

所以,我从这里尝试了Ivan C(下面的评论)提到的解决方案它也不起作用。应用该解决方案

let hello = warp::path::end().map(|name| format!("Hello"));

反过来导致此错误消息:

   [rustc E0599] [E] no method named `map` found for opaque type `impl warp::Filter+std::marker::Copy` in the current scope
method not found in `impl warp::Filter+std::marker::Copy`
note: the method `map` exists but the following trait bounds were not
satisfied: `impl warp::Filter+std::marker::Copy: std::iter::Iterator`

似乎只有在不需要根路由的情况下才使用扭曲路径进行路由,这只是一个显示停止器。

4

1 回答 1

1

这不会编译:

let hello = warp::path::end()
    .map(|name| format!("Hello"));

因为name如果您不再动态匹配路由路径的任何部分,那么闭包中的参数将来自哪里?如果您删除了未使用的name参数,并且format!也是不必要的,那么它可以工作:

use warp::Filter;

#[tokio::main]
async fn main() {
    let hello = warp::path::end()
        .map(|| "Hello");

    warp::serve(hello)
        .run(([127, 0, 0, 1], 3030))
        .await;
}

现在访问http://127.0.0.1:3030产生Hello

于 2020-12-28T13:35:17.730 回答