首页 > 解决方案 > 如何编写经线日志?

问题描述

我是 Rust 的新手,正在尝试使用https://docs.rs/warp/0.2.3/warp/index.html构建一个 Web 应用程序。

我努力了:

#[tokio::main]
async fn main() {
    // GET /hello/warp => 200 OK with body "Hello, warp!"

    let cors = warp::cors()
        .allow_origin("http://localhost:8090")
        .allow_methods(vec!["GET", "POST", "DELETE"]);

    let log = warp::log("dashbaord-svc");

    let hello = warp::path!("hello" / String)
        .with(cors)
        .with(log)
        .map(|name| format!("Hello, {}!", name));


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

编译器抱怨:

error[E0277]: `warp::filters::log::internal::Logged` doesn't implement `std::fmt::Display`
  --> src/main.rs:16:43
   |
16 |         .map(|name| format!("Hello, {}!", name));
   |                                           ^^^^ `warp::filters::log::internal::Logged` cannot be formatted with the default formatter
   |
   = help: the trait `std::fmt::Display` is not implemented for `warp::filters::log::internal::Logged`
   = note: in format strings you may be able to use `{:?}` (or {:#?} for pretty-print) instead
   = note: required by `std::fmt::Display::fmt`
   = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)  

我究竟做错了什么?

标签: rust

解决方案


    let hello = warp::path!("hello" / String)
    .with(cors)
    .with(log)
    .map(|name| format!("Hello, {}!", name));

过滤器传递到后续过滤器数据。在您的代码中,map 函数将从它之前的最后一个过滤器(即日志过滤器)接收数据,并将数据作为“名称”传递,其类型为“warp::filters::log::internal::Logged”。这种类型不能被格式化!或打印!使用 {},因为它没有实现 Display 特征。

过滤顺序很重要。在路径过滤器之后更改映射函数以接收路径参数作为“名称”:

    let hello = warp::path!("hello" / String)
    .map(|name| format!("Hello, {}!", name))
    .with(cors)
    .with(log);

推荐阅读