Skip to content

Instantly share code, notes, and snippets.

@willf
Last active October 1, 2015 02:38
Show Gist options
  • Save willf/1904573 to your computer and use it in GitHub Desktop.
Save willf/1904573 to your computer and use it in GitHub Desktop.
Resolve a (possible) redirect
require 'net/http'
def resolve(uri_str,limit=5)
$stderr.puts("Resolving #{uri_str}")
limit.times do |i|
uri = URI.parse(uri_str)
raise "No host given #{uri_str}" unless uri.host
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Head.new(uri.request_uri)
response = http.request(request)
# $stderr.puts("response: #{response.inspect}")
case response
when Net::HTTPSuccess then
return uri_str
when Net::HTTPRedirection then
uri_str = response['location']
raise "No redirection location given for #{uri_str}" if (not uri_str)
else
raise "Non-success/redirect response: " + response.inspect
end
end
raise "Too many retries; latest resolution was #{uri_str}"
end
#while (line=gets)
# url = line.strip
# begin
# x = resolve(url)
# puts [true,url,x].join("\t")
# rescue Exception => e
# puts [false, url, e].join("\t")
# end
# $stdout.flush
#end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment