Module rama::http::layer::request_id

Expand description

Set and propagate request ids.

§Example

use rama_http::layer::request_id::{
    SetRequestIdLayer, PropagateRequestIdLayer, MakeRequestId, RequestId,
};
use rama_http::{Body, Request, Response, header::HeaderName};
use rama_core::service::service_fn;
use rama_core::{Context, Service, Layer};
use rama_core::error::BoxError;
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>(&self, request: &Request<B>) -> Option<RequestId> {
        let request_id = self.counter
            .fetch_add(1, Ordering::AcqRel)
            .to_string()
            .parse()
            .unwrap();

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

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

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

let request = Request::new(Body::empty());
let response = svc.serve(Context::default(), request).await?;

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

Structs§

Traits§