Available on crate feature request-id only.
Expand description

Set and propagate request ids.

Example

use http::{Request, Response, header::HeaderName};
use tower_async::{Service, ServiceExt, ServiceBuilder};
use tower_async_http::request_id::{
    SetRequestIdLayer, PropagateRequestIdLayer, MakeRequestId, RequestId,
};
use hyper::Body;
use std::sync::{Arc, atomic::{AtomicU64, Ordering}};

// A `MakeRequestId` that increments an atomic counter
#[derive(Clone, Default)]
struct MyMakeRequestId {
    counter: Arc<AtomicU64>,
}

impl MakeRequestId for MyMakeRequestId {
    fn make_request_id<B>(&mut self, request: &Request<B>) -> Option<RequestId> {
        let request_id = self.counter
            .fetch_add(1, Ordering::SeqCst)
            .to_string()
            .parse()
            .unwrap();

        Some(RequestId::new(request_id))
    }
}

let x_request_id = HeaderName::from_static("x-request-id");

let mut svc = ServiceBuilder::new()
    // set `x-request-id` header on all requests
    .layer(SetRequestIdLayer::new(
        x_request_id.clone(),
        MyMakeRequestId::default(),
    ))
    // propagate `x-request-id` headers from request to response
    .layer(PropagateRequestIdLayer::new(x_request_id))
    .service(handler);

let request = Request::new(Body::empty());
let response = svc.call(request).await?;

assert_eq!(response.headers()["x-request-id"], "0");

Additional convenience methods are available on ServiceBuilderExt:

use tower_async_http::ServiceBuilderExt;

let mut svc = ServiceBuilder::new()
    .set_x_request_id(MyMakeRequestId::default())
    .propagate_x_request_id()
    .service(handler);

let request = Request::new(Body::empty());
let response = svc.call(request).await?;

assert_eq!(response.headers()["x-request-id"], "0");

See SetRequestId and PropagateRequestId for more details.

Doesn’t override existing headers

SetRequestId and PropagateRequestId wont override request ids if its already present on requests or responses. Among other things, this allows other middleware to conditionally set request ids and use the middleware in this module as a fallback.

Structs

Traits