Rust axum / hyper 请求局部变量

Rust axum / hyper request local variables

有没有办法将变量绑定到 Axum 请求?

特别是,我正在尝试将请求 ID 添加到每个跟踪事件。我可以像这样使用 tower::trace 中间件来做到这一点:

#[derive(Clone)]
pub struct RequestSpan;

impl<B> tower_http::trace::MakeSpan<B> for RequestSpan {
    fn make_span(&mut self, request: &http::Request<B>) -> tracing::Span {
        tracing::error_span!(
            "rq",
            id = %ulid::Ulid::new().to_string(),
            method = %request.method(),
            uri = %request.uri(),
            version = ?request.version(),
        )
    }
}

...

let middleware_stack = tower::ServiceBuilder::new()
    .layer(TraceLayer::new_for_http().make_span_with(RequestSpan))

它在服务器范围内工作,但我还需要将请求 ID 传递到外部任务队列中。有什么建议吗?

我把它变成了little crate following a solution from rustlang forum