Created
October 26, 2018 13:03
-
-
Save FooBarWidget/a9626c49e589b369659e53b54934b8ed to your computer and use it in GitHub Desktop.
This file contains hidden or 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
class DebugMiddleware | |
def initialize(app, message) | |
@app = app | |
@message = message | |
end | |
def call(*args) | |
STDERR.puts "BEGIN #{request_id} -- #{@message}" | |
status, headers, body = @app.call(*args) | |
consumed_body = consume_body(body) | |
[status, headers, consumed_body] | |
ensure | |
STDERR.puts "END #{request_id} -- #{@message} | status = #{status}, body size = #{get_body_size(consumed_body)}" | |
end | |
private | |
def request_id | |
Thread.current[:name] || Thread.current.object_id.to_s(36) | |
end | |
def consume_body(body) | |
return nil if body.nil? | |
return [body] if body.is_a?(String) | |
begin | |
result = [] | |
body.each do |part| | |
result << part | |
end | |
result | |
ensure | |
body.close if body.respond_to?(:close) | |
end | |
end | |
def get_body_size(consumed_body) | |
return 'nil' if consumed_body.nil? | |
result = 0 | |
consumed_body.each { |part| result += part.bytesize } | |
result | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment