Created
November 21, 2011 20:31
-
-
Save zunda/1383833 to your computer and use it in GitHub Desktop.
follow-redirect.rb: checks where shortened URLs are going
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
#!/usr/bin/ruby | |
# redirect.rb: checks where shortened URLs are going | |
# | |
# usage: ruby redirect.rb http://example.com/ | |
# shows URLs while being redirected | |
# | |
# Copyright 2011 (C) zunda <zunda at freeshell.org> | |
# | |
# Permission is granted for use, copying, modification, | |
# distribution, and distribution of modified versions of this | |
# work as long as the above copyright notice is included. | |
# | |
require 'uri' | |
require 'net/http' | |
def follow(url, redirects = 5, &block) | |
yield(url) | |
raise RuntimeError, "Too many redirects" if redirects == 0 | |
uri = URI.parse(url) | |
begin | |
Net::HTTP.start(uri.host, uri.port) do |http| | |
request = Net::HTTP::Head.new(uri.request_uri) | |
response = http.request(request) | |
case response | |
when Net::HTTPRedirection | |
follow(response['location'], redirects - 1, &block) | |
when Net::HTTPNotFound | |
raise RuntimeError, "Not Found" | |
end | |
end | |
rescue Errno::EHOSTUNREACH => e | |
raise RuntimeError, e | |
rescue Errno::ECONNREFUSED => e | |
raise RuntimeError, e | |
rescue Errno::ECONNRESET => e | |
raise RuntimeError, e | |
end | |
end | |
begin | |
follow(ARGV.shift) do |url| | |
puts url | |
end | |
rescue RuntimeError => e | |
puts e.message | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment