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),
	
	# There is no point including this:
	# '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.



25
26
27
28
29
30
# File 'lib/protocol/http/accept_encoding.rb', line 25

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

Instance Method Details

#call(request) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/protocol/http/accept_encoding.rb', line 32

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