Sha256: ca4328ffcc2cbacc6994d5cc69707d0d89c3b278a2623547b6030702c30dbe90

Contents?: true

Size: 1.19 KB

Versions: 30

Compression:

Stored size: 1.19 KB

Contents

# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2019-2023, by Samuel Williams.

require_relative 'middleware'

require_relative 'body/buffered'
require_relative 'body/inflate'

module Protocol
	module HTTP
		# Set a valid accept-encoding header and decode the response.
		class AcceptEncoding < Middleware
			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},
			}
			
			def initialize(app, wrappers = DEFAULT_WRAPPERS)
				super(app)
				
				@accept_encoding = wrappers.keys.join(', ')
				@wrappers = wrappers
			end
			
			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
		end
	end
end

Version data entries

30 entries across 30 versions & 1 rubygems

Version Path
protocol-http-0.36.0 lib/protocol/http/accept_encoding.rb
protocol-http-0.35.0 lib/protocol/http/accept_encoding.rb
protocol-http-0.34.0 lib/protocol/http/accept_encoding.rb
protocol-http-0.33.0 lib/protocol/http/accept_encoding.rb
protocol-http-0.32.0 lib/protocol/http/accept_encoding.rb
protocol-http-0.31.0 lib/protocol/http/accept_encoding.rb
protocol-http-0.30.0 lib/protocol/http/accept_encoding.rb
protocol-http-0.29.0 lib/protocol/http/accept_encoding.rb
protocol-http-0.28.2 lib/protocol/http/accept_encoding.rb
protocol-http-0.28.1 lib/protocol/http/accept_encoding.rb
protocol-http-0.28.0 lib/protocol/http/accept_encoding.rb
protocol-http-0.27.0 lib/protocol/http/accept_encoding.rb
protocol-http-0.26.8 lib/protocol/http/accept_encoding.rb
protocol-http-0.26.7 lib/protocol/http/accept_encoding.rb
protocol-http-0.26.6 lib/protocol/http/accept_encoding.rb
protocol-http-0.26.5 lib/protocol/http/accept_encoding.rb
protocol-http-0.26.4 lib/protocol/http/accept_encoding.rb
protocol-http-0.26.3 lib/protocol/http/accept_encoding.rb
protocol-http-0.26.2 lib/protocol/http/accept_encoding.rb
protocol-http-0.26.1 lib/protocol/http/accept_encoding.rb