Skip to content

Instantly share code, notes, and snippets.

@jmazzi
Created March 15, 2011 15:20
Show Gist options
  • Save jmazzi/870868 to your computer and use it in GitHub Desktop.
Save jmazzi/870868 to your computer and use it in GitHub Desktop.
Discard bad HTTP headers in Net::HTTP.
# Based on 1.9.2. Works in 1.8.7 too, though
module Net
class HTTP
@skip_bad_headers = false
class << self
def skip_bad_headers
@skip_bad_headers
end
def skip_bad_headers=(value)
@skip_bad_headers = value
end
end
end
class << HTTPResponse
def each_response_header(sock)
key = value = nil
while true
line = sock.readuntil("\n", true).sub(/\s+\z/, '')
break if line.empty?
if line[0] == ?\s or line[0] == ?\t and value
value << ' ' unless value.empty?
value << line.strip
else
tmp_key, tmp_value = line.strip.split(/\s*:\s*/, 2)
next if tmp_value.nil? && Net::HTTP.skip_bad_headers
yield key, value if key
key = tmp_key
value = tmp_value
raise HTTPBadResponse, 'wrong header line format' if value.nil?
end
end
yield key, value if key
end
end
end
require 'net_http_hacked'
# WHM is notorious for putting random STDOUT
# in their API output. This ignores it, but resets
# Net::HTTP to its default behavior after the request
begin
Net::HTTP.skip_bad_headers = true
http = Net::HTTP.new(uri.host, uri.port)
# ......
ensure
Net::HTTP.skip_bad_headers = false
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment