Skip to content

Instantly share code, notes, and snippets.

@ph
Created August 22, 2017 19:45
Show Gist options
  • Save ph/8d00dd05a90609cf83f25758b9839f3d to your computer and use it in GitHub Desktop.
Save ph/8d00dd05a90609cf83f25758b9839f3d to your computer and use it in GitHub Desktop.
# encoding: utf-8
require 'bundler/inline'
gemfile do
source 'https://rubygems.org'
gem 'rack'
gem 'sinatra', :require => 'sinatra/base'
gem 'pry'
end
# Use relistan's rack handler
# out of the box rack only gives use the rack deflater handler to return compressed
# response, this gist seems to offer the inverse and should work on all rack based app like sinatra or rails.
#
# https://gist.github.com/relistan/2109707
class CompressedRequests
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.delete('HTTP_CONTENT_ENCODING')
env['CONTENT_LENGTH'] = extracted.bytesize
env['rack.input'] = StringIO.new(extracted)
end
status, headers, response = @app.call(env)
return [status, headers, response]
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
rescue => e
require "pry";binding.pry
end
end
class TestingApp < Sinatra::Base
use CompressedRequests
post '/' do
if request.body.size > -1
request.body.rewind
puts "REQUEST BODY: #{request.body.read}"
else
puts "I did not receive anything?"
end
end
end
TestingApp.run!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment