Created
October 4, 2021 01:02
-
-
Save ignacio-chiazzo/050bc18d7e0f3577787cf737e6532406 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'securerandom' | |
module Middleware | |
class LogRequestId | |
REQUEST_ID = "X-Request-Id" | |
def initialize(app) | |
@app = app | |
end | |
def call(env) | |
request_id = generate_request_id(env) | |
@app.call(env).tap do |_status, headers, _body| | |
headers[@header] = request_id | |
end | |
@app.call(env) | |
end | |
private | |
def generate_request_id(env) | |
req = ActionDispatch::Request.new env | |
request_id = req.headers[REQUEST_ID] | |
if request_id.presence | |
request_id.gsub(/[^\w\-@]/, "").first(255) | |
else | |
build_request_id | |
end | |
end | |
def build_request_id | |
SecureRandom.uuid | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment