Class: Protocol::HTTP::AcceptEncoding

Inherits:
Middleware show all
Defined in:
lib/protocol/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},
}

Constants inherited from Methods

Methods::CONNECT, Methods::DELETE, Methods::GET, Methods::HEAD, Methods::LINK, Methods::OPTIONS, Methods::PATCH, Methods::POST, Methods::PUT, Methods::TRACE, Methods::UNLINK

Instance Attribute Summary

Attributes inherited from Middleware

#delegate

Instance Method Summary collapse

Methods inherited from Middleware

build, #close, for

Methods inherited from Methods

each, valid?

Constructor Details

#initialize(app, wrappers = DEFAULT_WRAPPERS) ⇒ AcceptEncoding

Returns a new instance of AcceptEncoding.



40
41
42
43
44
45
# File 'lib/protocol/http/accept_encoding.rb', line 40

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

Instance Method Details

#call(request) ⇒ Object



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

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