Last active
December 23, 2015 08:29
-
-
Save tdtds/6608110 to your computer and use it in GitHub Desktop.
Rack middleware of Request Decompression (gzip or deflate).
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 '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