Skip to content

Instantly share code, notes, and snippets.

@subdigital
Created October 20, 2010 00:05
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save subdigital/635471 to your computer and use it in GitHub Desktop.
Save subdigital/635471 to your computer and use it in GitHub Desktop.
Rack Middleware to automatically unzip gzipped/deflated POST data
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
@gotoAndBliss
Copy link

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.

@mestachs
Copy link

I suspect that the correct version, dealing better with utf-8 (chars vs bytes) :

   env['CONTENT_LENGTH'] = new_input.bytes.size

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment