Class: Degzipper::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/degzipper/middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Middleware



3
4
5
# File 'lib/degzipper/middleware.rb', line 3

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/degzipper/middleware.rb', line 15

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

#decode(input, content_encoding) ⇒ Object



28
29
30
31
32
33
# File 'lib/degzipper/middleware.rb', line 28

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

#encoding_handled?(env) ⇒ Boolean



11
12
13
# File 'lib/degzipper/middleware.rb', line 11

def encoding_handled?(env)
  ['gzip', 'deflate'].include? env['HTTP_CONTENT_ENCODING']
end

#method_handled?(env) ⇒ Boolean



7
8
9
# File 'lib/degzipper/middleware.rb', line 7

def method_handled?(env)
  !!(env['REQUEST_METHOD'] =~ /(POST|PUT|PATCH)/)
end