mirror of
https://github.com/tokio-rs/axum.git
synced 2026-08-23 00:00:15 +02:00
examples: Refactor request-id example (#3865)
This commit is contained in:
@@ -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"] }
|
||||
|
||||
@@ -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::<RequestId>().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);
|
||||
|
||||
Reference in New Issue
Block a user