Skip to content

Instantly share code, notes, and snippets.

@Slakah
Last active June 10, 2020 12:09
Show Gist options
  • Save Slakah/f5eb4fbe3c6cc1ed28f8bd66482cd566 to your computer and use it in GitHub Desktop.
Save Slakah/f5eb4fbe3c6cc1ed28f8bd66482cd566 to your computer and use it in GitHub Desktop.
Http4s X-Request-Id middleware
import java.util.UUID
import org.http4s.{Header, Http, Request, Response}
import cats.data.Kleisli
import cats.effect.Sync
import cats.implicits._
import org.http4s.syntax.string._
/**
* Propagate a `X-Request-Id` header to the response, generate a UUID
* when the `X-Request-Id` header is unset.
* https://devcenter.heroku.com/articles/http-request-id
*/
object RequestIdMiddleware {
def apply[G[_], F[_]](http: Http[G, F])(implicit G: Sync[G]): Http[G, F] =
Kleisli[G, Request[F], Response[F]] { req =>
for {
header <- req.headers.get("X-Request-ID".ci) match {
case None => G.delay[Header](Header("X-Request-ID", UUID.randomUUID().toString))
case Some(header) => G.pure[Header](header)
}
response <- http(req.putHeaders(header))
} yield response.putHeaders(header)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment