public
Last active

Rack Middleware to automatically unzip gzipped/deflated POST data

  • Download Gist
compress_requests.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
class CompressedRequests
def initialize(app)
@app = app
end
def call(env)
if env['REQUEST_METHOD'] =~ /(POST|PUT)/
if env.keys.include? 'HTTP_CONTENT_ENCODING'
input = env['rack.input'].read
new_input = decode(input, env['HTTP_CONTENT_ENCODING'])
env['rack.input'] = StringIO.new(new_input)
env['CONTENT_LENGTH'] = new_input.length
 
env.delete('HTTP_CONTENT_ENCODING')
end
end
 
status, headers, response = @app.call(env)
return [status, headers, response]
end
def decode(input, content_encoding)
if content_encoding == 'gzip'
z = Zlib::GzipReader.new(StringIO.new(input)).read
elsif content_encoding == 'deflate'
Zlib::Inflate.new.inflate new input
else
input
end
end
end

Out of curiosity, how do you instantiate CompressedRequests into the Rack? I'm trying to do the same, but my ['rack.input'] won't write.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.