Method: Mechanize::HTTP::Agent#response_content_encoding

Defined in:
lib/mechanize/http/agent.rb

#response_content_encoding(response, body_io) ⇒ Object



880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
# File 'lib/mechanize/http/agent.rb', line 880

def response_content_encoding response, body_io
  length = response.content_length ||
    case body_io
    when Tempfile, IO then
      body_io.stat.size
    else
      body_io.length
    end

  return body_io if length.zero?

  out_io = case response['Content-Encoding']
           when nil, 'none', '7bit', 'identity', "" then
             body_io
           when 'deflate' then
             content_encoding_inflate body_io
           when 'gzip', 'x-gzip' then
             content_encoding_gunzip body_io
           when 'br' then
             content_encoding_brotli body_io
           when 'zstd' then
             content_encoding_zstd body_io
           else
             raise Mechanize::Error,
               "unsupported content-encoding: #{response['Content-Encoding']}"
           end

  out_io.flush
  out_io.rewind

  out_io
rescue Zlib::Error => e
  message = String.new("error handling content-encoding #{response['Content-Encoding']}:")
  message << " #{e.message} (#{e.class})"
  raise Mechanize::Error, message
ensure
  begin
    if Tempfile === body_io and
       (StringIO === out_io or (out_io and out_io.path != body_io.path)) then
      body_io.close!
    end
  rescue IOError
    # HACK ruby 1.8 raises IOError when closing the stream
  end
end