diff --git a/Cargo.toml b/Cargo.toml index e8679c6bb..a3bc14e7e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -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" diff --git a/examples/request-id-response-header/Cargo.toml b/examples/request-id-response-header/Cargo.toml new file mode 100644 index 000000000..520428d59 --- /dev/null +++ b/examples/request-id-response-header/Cargo.toml @@ -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 = "../.." } diff --git a/examples/request-id-response-header/README.md b/examples/request-id-response-header/README.md new file mode 100644 index 000000000..a9f8e2c56 --- /dev/null +++ b/examples/request-id-response-header/README.md @@ -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 +... +``` diff --git a/examples/request-id-response-header/src/main.rs b/examples/request-id-response-header/src/main.rs new file mode 100644 index 000000000..5f40550a1 --- /dev/null +++ b/examples/request-id-response-header/src/main.rs @@ -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::().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(()) +}