class FaradayMiddleware::Gzip
A middleware that ensures that the client requests are sent with the headers that encourage servers to send compressed data, and then uncompresses it. The Content-Length will reflect the actual body length.
Constants
- ACCEPT_ENCODING
- ENCODINGS
Public Class Methods
new(app)
click to toggle source
# File lib/dacpclient/faraday/gzip.rb, line 12 def initialize(app) @app = app end
Public Instance Methods
call(curenv)
click to toggle source
# File lib/dacpclient/faraday/gzip.rb, line 16 def call(curenv) (curenv[:request_headers] ||= {})[ACCEPT_ENCODING] = ENCODINGS @app.call(curenv).on_complete do |env| encoding = env[:response_headers]['content-encoding'].to_s.downcase if %w(gzip deflate).include?(encoding) case encoding when 'gzip' env[:body] = uncompress_gzip(env[:body]) when 'deflate' env[:body] = Zlib::Inflate.inflate(env[:body]) end env[:response_headers].delete('content-encoding') env[:response_headers]['content-length'] = env[:body].length end end end
Private Instance Methods
uncompress_gzip(body)
click to toggle source
# File lib/dacpclient/faraday/gzip.rb, line 35 def uncompress_gzip(body) io = StringIO.new(body) gzip_reader = if '1.9'.respond_to?(:force_encoding) Zlib::GzipReader.new(io, encoding: 'ASCII-8BIT') else Zlib::GzipReader.new(io) end gzip_reader.read end