rack middleware, best way to replace request body?

46 views
Skip to first unread message

Stephen Bannasch

unread,
Aug 4, 2009, 10:42:23 AM8/4/09
to rack-...@googlegroups.com
I like to create a rack middleware filter that will automatically
decompress a request with a content encoding of 'b64gzip' before
passing it on.

What's the best way for a rack middleware filter to replace the
request bosy with an uncompressed version?

FYI, this is what my code looks like now -- it works except for the
part of actualyy replacing the request body ;-)

module Rack

class ExpandB64Gzip
def initialize(app)
@app = app
end

def call(env)
@compressed = env['HTTP_CONTENT_ENCODING'] == "b64gzip"
@app.call(env)
end

def each(&block)
if @compressed
req = Rack::Request.new(env)
decompressed_body = b64gzip_decompress_body(req.body)
debugger
req.body = decompressed_body
end

end

def b64gzip_decompress_body(body)
Zlib::GzipReader.new(StringIO.new(B64::B64.decode(body.read))).read
end
end
end

module B64
class B64
def self.folding_encode(str, eol = "\n", limit = 60)
[str].pack('m')
end

def self.encode(str)
[str].pack('m').tr( "\r\n", '')
end

def self.decode(str, strict = false)
str.unpack('m').first
end
end
end

Reply all
Reply to author
Forward
0 new messages