lib/itrigga/net_helper.rb in itrigga-net_helper-0.0.3 vs lib/itrigga/net_helper.rb in itrigga-net_helper-0.1.0

- old
+ new

@@ -7,10 +7,14 @@ module Itrigga module NetHelper module_function + + def typhoeus_present? + defined?(Typhoeus) + end def do_get(url, time_out=5, retries_on_timeout=5, max_redirects = 3) retrycount = 0 resp = nil begin @@ -26,13 +30,58 @@ raise IOError.new( "HTTP request timed out #{retrycount} times" ) end end end + + def typhoeus_request( opts={} ) + opts[:timeout] ||= 30000 # ms + opts[:follow_location] ||= true + opts[:disable_ssl_peer_verification] = true if opts[:disable_ssl_peer_verification].nil? + + request = Typhoeus::Request.new(opts[:url], opts) + + request.on_complete do |response| + if response.success? + return response.body + elsif response.timed_out? + # aw hell no + log("got a time out") + elsif response.code == 0 + # Could not get an http response, something's wrong. + log(response.curl_error_message) + else + # Received a non-successful http response. + log("HTTP request failed: " + response.code.to_s) + end + end + + end + + def get_response( url ) + if typhoeus_present? + typhoeus_request( url ) + else + Net::HTTP.get_response(URI.parse(url)) + end + end def get_with_timeout( url, time_out) + resp = nil + if defined?(SystemTimer) + resp = SystemTimer.timeout_after(time_out) do + get_response(url) + end + else + resp = timeout(time_out) do + get_response(url) + end + end + resp + end + resp = timeout(time_out) do - Net::HTTP.get_response(URI.parse(url)) + end resp end