Skip to content

Instantly share code, notes, and snippets.

@tdtds
Last active December 23, 2015 08:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tdtds/6608110 to your computer and use it in GitHub Desktop.
Save tdtds/6608110 to your computer and use it in GitHub Desktop.
Rack middleware of Request Decompression (gzip or deflate).
require 'zlib'
module Rack
class UnknownCompressMethod < StandardError; end
class RequestDecompressor
def initialize(app)
@app = app
end
def call(env)
req = Rack::Request.new(env)
env['rack.input'] = decompress(req.body, env['HTTP_CONTENT_ENCODING'])
@app.call(env)
end
def decompress(body, method)
case method
when 'gzip'
Zlib::GzipReader.wrap(StringIO.new body.read)
when 'deflate'
StringIO.new(Zlib::Inflate.inflate(body.read))
when nil
body
else # unknown compressing method
raise Rack::UnknownCompressMethod.new("unknown compress method '#{method}'.")
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment