1
0
mirror of https://github.com/actix/actix-extras.git synced 2025-02-22 18:33:18 +01:00

Add request-id header example (#108)

* Add request-id header example

* Apply cargo fmt
This commit is contained in:
Valentin Brandl 2023-06-16 17:06:53 +02:00 committed by GitHub
parent 20a85b2a08
commit f8b7ca2a5a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 77 additions and 1 deletions

View File

@ -1,5 +1,5 @@
[workspace] [workspace]
members = [".", "examples/opentelemetry", "examples/custom-root-span"] members = [".", "examples/opentelemetry", "examples/custom-root-span", "examples/request-id-response-header"]
[package] [package]
name = "tracing-actix-web" name = "tracing-actix-web"

View File

@ -0,0 +1,10 @@
[package]
name = "request-id-response-header"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
actix-web = "4"
tracing-actix-web = { path = "../.." }

View File

@ -0,0 +1,25 @@
# Request ID in Response Header
This example shows how to set the `RequestId` as a response header.
## Running
You can launch this example with
```bash
cargo run
```
An `actix-web` application will be listening on port `8080`.
You can fire requests to it with:
```bash
curl -v http://localhost:8080/hello
```
```text
...
< HTTP/1.1 200 OK
< content-length: 12
< x-request-id: 1d5c5448-44d2-4051-ab59-985868875f94
...
```

View File

@ -0,0 +1,41 @@
use actix_web::{
dev::Service,
http::header::{HeaderName, HeaderValue},
web, App, HttpMessage, HttpServer,
};
use std::io;
use tracing_actix_web::{RequestId, TracingLogger};
async fn hello() -> &'static str {
"Hello world!"
}
#[actix_web::main]
async fn main() -> io::Result<()> {
HttpServer::new(move || {
App::new()
// set the request id in the `x-request-id` response header
.wrap_fn(|req, srv| {
let request_id = req.extensions().get::<RequestId>().copied();
let res = srv.call(req);
async move {
let mut res = res.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)
}
})
.wrap(TracingLogger::default())
.service(web::resource("/hello").to(hello))
})
.bind("127.0.0.1:8080")?
.run()
.await?;
Ok(())
}