Skip to content

Commit

Permalink
Add request-id header example (LukeMathWalker#108)
Browse files Browse the repository at this point in the history
* Add request-id header example

* Apply cargo fmt
  • Loading branch information
vbrandl authored Jun 16, 2023
1 parent 20a85b2 commit f8b7ca2
Show file tree
Hide file tree
Showing 4 changed files with 77 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[workspace]
members = [".", "examples/opentelemetry", "examples/custom-root-span"]
members = [".", "examples/opentelemetry", "examples/custom-root-span", "examples/request-id-response-header"]

[package]
name = "tracing-actix-web"
Expand Down
10 changes: 10 additions & 0 deletions examples/request-id-response-header/Cargo.toml
Original file line number Diff line number Diff line change
@@ -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 = "../.." }
25 changes: 25 additions & 0 deletions examples/request-id-response-header/README.md
Original file line number Diff line number Diff line change
@@ -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
...
```
41 changes: 41 additions & 0 deletions examples/request-id-response-header/src/main.rs
Original file line number Diff line number Diff line change
@@ -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(())
}

0 comments on commit f8b7ca2

Please sign in to comment.