Last active
October 1, 2015 02:38
-
-
Save willf/1904573 to your computer and use it in GitHub Desktop.
Resolve a (possible) redirect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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