Class: Excon::Middleware::Decompress

Inherits:
Base
  • Object
show all
Defined in:
lib/excon/middlewares/decompress.rb

Constant Summary collapse

INFLATE_ZLIB_OR_GZIP =

Zlib::MAX_WBITS + 32

47
INFLATE_RAW =

Zlib::MAX_WBITS * -1

-15 # Zlib::MAX_WBITS * -1

Instance Method Summary collapse

Methods inherited from Base

#error_call, #initialize, valid_parameter_keys

Constructor Details

This class inherits a constructor from Excon::Middleware::Base

Instance Method Details

#request_call(datum) ⇒ Object



9
10
11
12
13
14
15
# File 'lib/excon/middlewares/decompress.rb', line 9

def request_call(datum)
  unless datum.key?(:response_block)
    key = datum[:headers].keys.detect { |k| k.to_s.casecmp?('Accept-Encoding') } || 'Accept-Encoding'
    datum[:headers][key] = 'deflate, gzip' if datum[:headers][key].to_s.empty?
  end
  @stack.request_call(datum)
end

#response_call(datum) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/excon/middlewares/decompress.rb', line 17

def response_call(datum)
  body = datum[:response][:body]
  if !(datum.key?(:response_block) || body.nil? || body.empty?) &&
     (key = datum[:response][:headers].keys.detect { |k| k.casecmp?('Content-Encoding') })
    encodings = Utils.split_header_value(datum[:response][:headers][key])
    if encodings&.last&.casecmp?('deflate')
      datum[:response][:body] = begin
        Zlib::Inflate.new(INFLATE_ZLIB_OR_GZIP).inflate(body)
      rescue Zlib::DataError # fallback to raw on error
        Zlib::Inflate.new(INFLATE_RAW).inflate(body)
      end
      encodings.pop
    elsif encodings&.last&.casecmp?('gzip') || encodings&.last&.casecmp?('x-gzip')
      datum[:response][:body] = Zlib::GzipReader.new(StringIO.new(body)).read
      encodings.pop
    end
    datum[:response][:headers][key] = encodings.join(', ')
  end
  @stack.response_call(datum)
end