Request Id
Request Id 中间件是比较灵活的,生成器(IdGenerator) 用于生成 ID, 可以定义自己的 ID 生成器,只要实现 IdGenerator
这个 trait. 默认提供生成器是 UlidGenerator
.
另外你可以控制是否覆盖现在的已经存在的 requestid
. 还可以设置 header_name
等, 具体请查看文档.
示例代码
use salvo::prelude::*;
#[handler]
async fn hello(req: &mut Request) -> String {
format!("Request id: {:?}", req.header::<String>("x-request-id"))
}
#[tokio::main]
async fn main() {
tracing_subscriber::fmt().init();
let acceptor = TcpListener::new("0.0.0.0:5800").bind().await;
let router = Router::new().hoop(RequestId::new()).get(hello);
Server::new(acceptor).serve(router).await;
}
[package]
name = "example-request-id"
version.workspace = true
edition.workspace = true
publish.workspace = true
[dependencies]
salvo = { workspace = true, features = ["request-id"]}
tokio = { workspace = true, features = ["macros"] }
tracing.workspace = true
tracing-subscriber.workspace = true