Class: SplitIoClient::FaradayMiddleware::Gzip
- Inherits:
-
Faraday::Middleware
- Object
- Faraday::Middleware
- SplitIoClient::FaradayMiddleware::Gzip
- Defined in:
- lib/splitclient-rb/engine/api/faraday_middleware/gzip.rb
Constant Summary collapse
- ACCEPT_ENCODING =
'Accept-Encoding'
- CONTENT_ENCODING =
'Content-Encoding'
- CONTENT_LENGTH =
'Content-Length'
- SUPPORTED_ENCODINGS =
'gzip,deflate'
- RUBY_ENCODING =
'1.9'.respond_to?(:force_encoding)
Instance Method Summary collapse
- #call(env) ⇒ Object
- #inflate(body) ⇒ Object
- #reset_body(env) ⇒ Object
- #uncompress_gzip(body) ⇒ Object
Instance Method Details
#call(env) ⇒ Object
14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/splitclient-rb/engine/api/faraday_middleware/gzip.rb', line 14 def call(env) env[:request_headers][ACCEPT_ENCODING] ||= SUPPORTED_ENCODINGS @app.call(env).on_complete do |response_env| case response_env[:response_headers][CONTENT_ENCODING] when 'gzip' reset_body(response_env, &method(:uncompress_gzip)) when 'deflate' reset_body(response_env, &method(:inflate)) end end end |
#inflate(body) ⇒ Object
42 43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/splitclient-rb/engine/api/faraday_middleware/gzip.rb', line 42 def inflate(body) # Inflate as a DEFLATE (RFC 1950+RFC 1951) stream Zlib::Inflate.inflate(body) rescue Zlib::DataError # Fall back to inflating as a "raw" deflate stream which # Microsoft servers return inflate = Zlib::Inflate.new(-Zlib::MAX_WBITS) begin inflate.inflate(body) ensure inflate.close end end |
#reset_body(env) ⇒ Object
26 27 28 29 30 |
# File 'lib/splitclient-rb/engine/api/faraday_middleware/gzip.rb', line 26 def reset_body(env) env[:body] = yield(env[:body]) env[:response_headers].delete(CONTENT_ENCODING) env[:response_headers][CONTENT_LENGTH] = env[:body].length end |
#uncompress_gzip(body) ⇒ Object
32 33 34 35 36 37 38 39 40 |
# File 'lib/splitclient-rb/engine/api/faraday_middleware/gzip.rb', line 32 def uncompress_gzip(body) io = StringIO.new(body) gzip_reader = if RUBY_ENCODING Zlib::GzipReader.new(io, encoding: 'ASCII-8BIT') else Zlib::GzipReader.new(io) end gzip_reader.read end |