#---------------------------------------------------------
# Module: Proxy
#
# Purpose: mixin for making HTTP requests
# and handling them appropriately
#
# Libs: Net:HTTP, URI, CGI
#---------------------------------------------------------
module Proxy
require 'net/http'
require 'uri'
require 'cgi'
#generic proxy server exception (such as non handled HTTP response codes)
class ProxyServerException < RuntimeError
end
def http_redirect_limit
10
end
class HttpRedirectToDeepException < RuntimeError
attr_reader :current_limit
def initialize(limit=http_redirect_limit)
@current_limit = limit
end
end
# returns [(boolean) error, (class) NET::HTTPResponse]
def call(rawUrl)
begin
rawUrl = CGI::unescape rawUrl
def fetch(uri_str, limit = http_redirect_limit)
raise HttpRedirectToDeepException.new(limit), 'HTTP redirect too deep' if limit == 0
response = Net::HTTP.get_response(URI.parse(uri_str))
case response
when Net::HTTPSuccess then response
when Net::HTTPRedirection then fetch(response['location'], limit - 1)
when Net::HTTPNotFound then response
when Net::HTTPInternalServerError then response
else
response.error!
end
end
response = {:error => false, :object => fetch(rawUrl)}
rescue Exception => e
response = {:error => true, :object => e}
ensure
response
end
end
end