expression
REST: propagate a server request identifier
A server-generated request ID can appear on the response and in protected diagnostic logs. This middleware deliberately uses a fixed synthetic value for a single deterministic test; production needs unique IDs, trusted ingress handling and an explicit logging policy. Tower HTTP also provides request-ID layers. Standalone synthetic example. Expected stdout (not executed): test-17 Common mistake: Reusing this fixed test ID for real requests or using it for authorization.
Formal Syntax & Structure
rust syntaxrust
response.headers_mut().insert("x-request-id", value)Working Example
Example Snippetrust
use axum::{Router, Json, body::{Body, to_bytes}, http::{Request, StatusCode}};use serde::{Deserialize, Serialize};use tower::ServiceExt;
#[tokio::main(flavor = "current_thread")]async fn main() { use axum::{middleware::{from_fn, Next}, response::Response, http::HeaderValue, routing::get}; async fn correlate(mut req: Request<Body>, next: Next) -> Response { let id = HeaderValue::from_static("test-17"); req.headers_mut().insert("x-request-id", id.clone()); let mut res = next.run(req).await; res.headers_mut().insert("x-request-id", id); res } let app = Router::new().route("/", get(|| async { "ok" })).layer(from_fn(correlate)); let res = app.oneshot(Request::builder().header("x-request-id", "untrusted").body(Body::empty()).unwrap()).await.unwrap(); println!("{}", res.headers()["x-request-id"].to_str().unwrap());}