RequestId as Response Header
vbrandl opened this issue · 3 comments
vbrandl commented
I want to add the RequestId
to every response as a header x-request-id
.
What would be the easiest way to do that? Do I have to implement a custom middleware? Would this be a good feature addition to tracing-actix-web
directly?
LukeMathWalker commented
A very simple custom middleware should do the job.
This is not a feature I'm planning to add right now.
vbrandl commented
Ok it was easier than expected. The following code adds the header, if you want to add it to your examples:
App::new()
.wrap_fn(|req, srv| {
let request_id = req.extensions().get::<RequestId>().copied();
let fut = srv.call(req);
async move {
let mut res = fut.await?;
if let Some(request_id) = request_id {
res.headers_mut().insert(
HeaderName::from_static("x-request-id"),
// this unwrap never fails, since UUIDs are valid ASCII strings
HeaderValue::from_str(&request_id.to_string()).unwrap(),
);
}
Ok(res)
}
})
LukeMathWalker commented
Feel free to submit a PR with the example 👍🏻