Request Id
Request Id middleware is flexible. The generator (IdGenerator) is used to generate IDs. You can define your own ID generator as long as you implement the IdGenerator
trait. The default generator provided is UlidGenerator
.
In addition, you can control whether to overwrite the existing requestid
. You can also set header_name
, etc. For details, please see the document.
Sample code
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