feat(middleware): return request ID in response header (#214)

This commit is contained in:
Sanchith Hegde
2022-12-22 12:19:26 +05:30
committed by GitHub
parent 6fb19c7f4a
commit 349036bff3
2 changed files with 63 additions and 0 deletions

View File

@ -35,6 +35,7 @@ pub(crate) mod macros;
pub mod routes; pub mod routes;
pub mod scheduler; pub mod scheduler;
mod middleware;
pub mod services; pub mod services;
pub mod types; pub mod types;
pub mod utils; pub mod utils;
@ -95,6 +96,7 @@ pub fn mk_app(
let mut server_app = actix_web::App::new() let mut server_app = actix_web::App::new()
.app_data(json_cfg) .app_data(json_cfg)
.wrap(middleware::RequestId)
.wrap(router_env::tracing_actix_web::TracingLogger::default()) .wrap(router_env::tracing_actix_web::TracingLogger::default())
.wrap(ErrorHandlers::new().handler( .wrap(ErrorHandlers::new().handler(
StatusCode::NOT_FOUND, StatusCode::NOT_FOUND,

View File

@ -0,0 +1,61 @@
/// Middleware to include request ID in response header.
pub(crate) struct RequestId;
impl<S, B> actix_web::dev::Transform<S, actix_web::dev::ServiceRequest> for RequestId
where
S: actix_web::dev::Service<
actix_web::dev::ServiceRequest,
Response = actix_web::dev::ServiceResponse<B>,
Error = actix_web::Error,
>,
S::Future: 'static,
B: 'static,
{
type Response = actix_web::dev::ServiceResponse<B>;
type Error = actix_web::Error;
type Transform = RequestIdMiddleware<S>;
type InitError = ();
type Future = std::future::Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
std::future::ready(Ok(RequestIdMiddleware { service }))
}
}
pub(crate) struct RequestIdMiddleware<S> {
service: S,
}
impl<S, B> actix_web::dev::Service<actix_web::dev::ServiceRequest> for RequestIdMiddleware<S>
where
S: actix_web::dev::Service<
actix_web::dev::ServiceRequest,
Response = actix_web::dev::ServiceResponse<B>,
Error = actix_web::Error,
>,
S::Future: 'static,
B: 'static,
{
type Response = actix_web::dev::ServiceResponse<B>;
type Error = actix_web::Error;
type Future = futures::future::LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
actix_web::dev::forward_ready!(service);
fn call(&self, req: actix_web::dev::ServiceRequest) -> Self::Future {
let mut req = req;
let request_id_fut = req.extract::<router_env::tracing_actix_web::RequestId>();
let response_fut = self.service.call(req);
Box::pin(async move {
let request_id = request_id_fut.await?;
let mut response = response_fut.await?;
response.headers_mut().append(
http::header::HeaderName::from_static("x-request-id"),
http::HeaderValue::from_str(&request_id.as_hyphenated().to_string())?,
);
Ok(response)
})
}
}