Skip to content

Instantly share code, notes, and snippets.

@zerobearing2
Forked from relistan/compress_requests.rb
Last active August 29, 2015 14:05
Show Gist options
  • Save zerobearing2/e935a557a5584aaaef19 to your computer and use it in GitHub Desktop.
Save zerobearing2/e935a557a5584aaaef19 to your computer and use it in GitHub Desktop.
Rack middleware to deflate/unzip requests
module Rack
#
# Deflate/ungzip request body
#
class DeflateRequest
def initialize(app)
@app = app
end
def method_handled?(env)
!!(env['REQUEST_METHOD'] =~ /(POST|PUT)/)
end
def encoding_handled?(env)
['gzip', 'deflate'].include? env['HTTP_CONTENT_ENCODING']
end
def call(env)
if method_handled?(env) && encoding_handled?(env)
extracted = decode(env['rack.input'], env['HTTP_CONTENT_ENCODING'])
env['X_REQUEST_CONTENT_ENCODING'] = env.delete('HTTP_CONTENT_ENCODING')
env['CONTENT_LENGTH'] = extracted.bytesize
env['rack.input'] = StringIO.new(extracted)
end
@app.call(env)
end
def decode(input, content_encoding)
case content_encoding
when 'gzip' then Zlib::GzipReader.new(input).read
when 'deflate' then Zlib::Inflate.inflate(input.read)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment