Class: Async::HTTP::AcceptEncoding

Inherits:
Middleware show all
Defined in:
lib/async/http/accept_encoding.rb

Overview

Set a valid accept-encoding header and decode the response.

Constant Summary collapse

ACCEPT_ENCODING =
'accept-encoding'.freeze
CONTENT_ENCODING =
'content-encoding'.freeze
DEFAULT_WRAPPERS =
{
  'gzip' => Body::Inflate.method(:for),
  'identity' => ->(body){body},
}

Instance Attribute Summary

Attributes inherited from Middleware

#delegate

Instance Method Summary collapse

Methods inherited from Middleware

build, #close

Constructor Details

#initialize(app, wrappers = DEFAULT_WRAPPERS) ⇒ AcceptEncoding

Returns a new instance of AcceptEncoding.



38
39
40
41
42
43
# File 'lib/async/http/accept_encoding.rb', line 38

def initialize(app, wrappers = DEFAULT_WRAPPERS)
  super(app)
  
  @accept_encoding = wrappers.keys.join(', ')
  @wrappers = wrappers
end

Instance Method Details

#call(request) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/async/http/accept_encoding.rb', line 45

def call(request)
  request.headers[ACCEPT_ENCODING] = @accept_encoding
  
  response = super
  
  if body = response.body and !body.empty? and content_encoding = response.headers.delete(CONTENT_ENCODING)
    # We want to unwrap all encodings
    content_encoding.reverse_each do |name|
      if wrapper = @wrappers[name]
        body = wrapper.call(body)
      end
    end
    
    response.body = body
  end
  
  return response
end