Skip to content

Instantly share code, notes, and snippets.

@jacortinas
Created April 23, 2010 23:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jacortinas/377276 to your computer and use it in GitHub Desktop.
Save jacortinas/377276 to your computer and use it in GitHub Desktop.
require 'net/http'
# two_deep points to the bitly url underneath here
two_deep = 'http://tinyurl.com/679cto'
# one_deep points to google
one_deep = 'http://bit.ly/2V6CFi'
def follow_url(url, max_depth = 10)
url = URI.parse(url)
depth = 0
res = nil
# Starts an HTTP connection, no data requested yet
Net::HTTP.start(url.host, url.port) do |http|
# request only the header information of the path of the url
res = http.head(url.path)
# run until the response code is a 200, not a 307
until res.code_type == Net::HTTPOK
raise "Max depth of #{max_depth} was reached, give up!" if depth == max_depth
# if response is 307, follow the url, reassign variables and do it again
if res.code_type == Net::HTTPMovedPermanently
# the location header only exists on responses that are 307's
# it contains the next location that the client should redirect to
url = URI.parse(res['location'])
Net::HTTP.start(url.host, url.port) do |http|
depth += 1
res = http.head(url.path)
end
else
# no normal response code was returned, bail out
raise "Shenanigans! #{res.code_type}"
end
end
return url, depth
end
end
puts follow_url(two_deep)
puts follow_url(one_deep)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment