lib/httpx/plugins/compression.rb in httpx-0.3.1 vs lib/httpx/plugins/compression.rb in httpx-0.4.0

- old
+ new

@@ -1,36 +1,46 @@ # frozen_string_literal: true module HTTPX module Plugins + # + # This plugin adds compression support. Namely it: + # + # * Compresses the request body when passed a supported "Content-Encoding" mime-type; + # * Decompresses the response body from a supported "Content-Encoding" mime-type; + # + # It supports both *gzip* and *deflate*. + # module Compression extend Registry - def self.configure(klass, *) + def self.load_dependencies(klass, *) klass.plugin(:"compression/gzip") klass.plugin(:"compression/deflate") end - module InstanceMethods - def initialize(opts = {}) - super(opts.merge(headers: { "accept-encoding" => Compression.registry.keys })) - end + def self.extra_options(options) + options.merge(headers: { "accept-encoding" => Compression.registry.keys }) end module RequestBodyMethods def initialize(*) super return if @body.nil? + @headers.get("content-encoding").each do |encoding| @body = Encoder.new(@body, Compression.registry(encoding).encoder) end @headers["content-length"] = @body.bytesize unless chunked? end end module ResponseBodyMethods def initialize(*) super + + return unless @headers.key?("content-encoding") + @_decoders = @headers.get("content-encoding").map do |encoding| Compression.registry(encoding).decoder end @_compressed_length = if @headers.key?("content-length") @headers["content-length"].to_i @@ -38,17 +48,22 @@ Float::INFINITY end end def write(chunk) + return super unless defined?(@_compressed_length) + @_compressed_length -= chunk.bytesize chunk = decompress(chunk) super(chunk) end def close super + + return unless defined?(@_decoders) + @_decoders.each(&:close) end private @@ -68,10 +83,11 @@ @deflater = deflater end def each(&blk) return enum_for(__method__) unless block_given? + unless @buffer.size.zero? @buffer.rewind return @buffer.each(&blk) end deflate(&blk) @@ -95,9 +111,10 @@ private def deflate(&blk) return unless @buffer.size.zero? + @body.rewind @deflater.deflate(@body, @buffer, chunk_size: 16_384, &blk) end end