rust - 如何编写经线日志?
问题描述
我是 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)
我究竟做错了什么?
解决方案
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);
推荐阅读
- c# - 当父级变为空时,uwp 绑定到子属性不会更新
- visual-studio-code - 有没有办法在 BPMN Kogito 工具 VSCode 扩展上显示任务输入/输出?
- javascript - 同一用户在混合类型数组中对图像上传进行分组
- entity-framework - 当我不希望它时,EF Core 加载关系
- mysql - MYSQL 搜索 WHERE 值在 json_encoded 字段中
- mongodb - 如何使用 Debezium MongoDB Source Connector 将 JSON 值转换为 Kafka 消息键?
- tensorflow - tflite模型的反向转换
- excel - excel查找值并替换另一个单元格的值
- r - 如何解决在 R 上安装软件包的“写入错误”?
- spring-boot - Spring Boot 和 Spring Data Moore 发布