Created
October 23, 2014 16:04
-
-
Save justindossey/7c6e0a62ec34ce0bf317 to your computer and use it in GitHub Desktop.
test various methods of performing HTTP requests from behind a proxy
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/env ruby | |
require 'net/http' | |
require 'open-uri' | |
require 'rubygems' | |
require 'http' # this is the http gem | |
require 'faraday' | |
class ProxyTest | |
def initialize(url) | |
@url = url | |
@uri = URI(@url) | |
@methods = [:net_http_new, :net_http_start, | |
:net_http_get_request, :net_http_get, :open_uri, | |
:http_gem_get, :http_gem_via_get, :faraday_get | |
] | |
@padding = @methods.max_by {|x| x.to_s.length }.length | |
end | |
def run | |
@methods.each do |m| | |
begin | |
ENV['no_proxy'] = '' | |
ENV['NO_PROXY'] = ENV['no_proxy'] | |
send(m) | |
printf "%-#{@padding}s PASSED with proxy\n", m | |
ENV['no_proxy'] = @uri.host | |
ENV['NO_PROXY'] = ENV['no_proxy'] | |
begin | |
send(m) | |
printf "%-#{@padding}s FAILED with no_proxy\n", m | |
rescue | |
printf "%-#{@padding}s PASSED with no_proxy\n", m | |
end | |
rescue | |
printf "%-#{@padding}s FAILED with proxy\n", m | |
end | |
end | |
end | |
def net_http_new | |
Net::HTTP.new(@uri.host, @uri.port).start do |http| | |
http.request Net::HTTP::Get.new(@uri) | |
end | |
end | |
def net_http_start | |
Net::HTTP.start(@uri.host, @uri.port) do |http| | |
http.request Net::HTTP::Get.new(@uri) | |
end | |
end | |
def net_http_get_request | |
Net::HTTP.get_request(@url) | |
end | |
def net_http_get | |
Net::HTTP.get URI(@url) | |
end | |
def open_uri | |
open(@url) {|x| x.read } | |
end | |
def http_gem_get | |
HTTP.get(@url).to_s | |
end | |
# use the HTTP gem but do the proxy detection by hand | |
def http_gem_via_get | |
proxy_args = [] | |
proxy_envvar = "#{@uri.scheme}_proxy" | |
proxy = ENV[proxy_envvar] || ENV[proxy_envvar.upcase] | |
if proxy | |
uri = URI(proxy) | |
proxy_args = [uri.host, uri.port, uri.user, uri.password] | |
end | |
HTTP.via(*proxy_args).get(@url) | |
end | |
def faraday_get | |
Faraday.get(@url) | |
end | |
end | |
if $PROGRAM_NAME == __FILE__ | |
url = 'http://www.ruby-doc.org/stdlib-2.1.3/libdoc/net/http/rdoc/Net/HTTP.html' | |
ProxyTest.new(url).run | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
My output: