From 97def9590aaea9c70f8156f2438d1da6ebcfaf68 Mon Sep 17 00:00:00 2001 From: tottoto Date: Sat, 15 Aug 2026 17:40:51 +0900 Subject: [PATCH] examples: Refactor request-id example (#3865) --- examples/request-id/Cargo.toml | 2 +- examples/request-id/src/main.rs | 37 +++++++++------------------------ 2 files changed, 11 insertions(+), 28 deletions(-) diff --git a/examples/request-id/Cargo.toml b/examples/request-id/Cargo.toml index 43308c33..889fe625 100644 --- a/examples/request-id/Cargo.toml +++ b/examples/request-id/Cargo.toml @@ -8,6 +8,6 @@ publish = false axum = { path = "../../axum" } tokio = { version = "1.0", features = ["full"] } tower = "0.5.2" -tower-http = { version = "0.6", features = ["request-id", "trace"] } +tower-http = { version = "0.6", features = ["request-id", "trace", "util"] } tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } diff --git a/examples/request-id/src/main.rs b/examples/request-id/src/main.rs index 4c6874b6..ca33e6a0 100644 --- a/examples/request-id/src/main.rs +++ b/examples/request-id/src/main.rs @@ -4,22 +4,16 @@ //! cargo run -p example-request-id //! ``` -use axum::{ - http::{HeaderName, Request}, - response::Html, - routing::get, - Router, -}; +use axum::{http::Request, response::Html, routing::get, Router}; use tower::ServiceBuilder; use tower_http::{ - request_id::{MakeRequestUuid, PropagateRequestIdLayer, SetRequestIdLayer}, + request_id::{MakeRequestUuid, RequestId}, trace::TraceLayer, + ServiceBuilderExt, }; -use tracing::{error, info, info_span}; +use tracing::{info, info_span}; use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt}; -const REQUEST_ID_HEADER: &str = "x-request-id"; - #[tokio::main] async fn main() { tracing_subscriber::registry() @@ -37,32 +31,21 @@ async fn main() { .with(tracing_subscriber::fmt::layer()) .init(); - let x_request_id = HeaderName::from_static(REQUEST_ID_HEADER); - let middleware = ServiceBuilder::new() - .layer(SetRequestIdLayer::new( - x_request_id.clone(), - MakeRequestUuid, - )) + .set_x_request_id(MakeRequestUuid) .layer( TraceLayer::new_for_http().make_span_with(|request: &Request<_>| { // Log the request id as generated. - let request_id = request.headers().get(REQUEST_ID_HEADER); + let request_id = request.extensions().get::().unwrap(); - match request_id { - Some(request_id) => info_span!( - "http_request", - request_id = ?request_id, - ), - None => { - error!("could not extract request_id"); - info_span!("http_request") - } + match request_id.header_value().to_str() { + Ok(request_id) => info_span!("http_request", request_id), + Err(_) => info_span!("http_request", request_id = ?request_id), } }), ) // send headers from request to response headers - .layer(PropagateRequestIdLayer::new(x_request_id)); + .propagate_x_request_id(); // build our application with a route let app = Router::new().route("/", get(handler)).layer(middleware);