Skip to content

Instantly share code, notes, and snippets.

@justindossey
Created October 23, 2014 16:04
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 justindossey/7c6e0a62ec34ce0bf317 to your computer and use it in GitHub Desktop.
Save justindossey/7c6e0a62ec34ce0bf317 to your computer and use it in GitHub Desktop.
test various methods of performing HTTP requests from behind a proxy
#!/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
@justindossey
Copy link
Author

My output:

net_http_new         PASSED with proxy
net_http_new         PASSED with no_proxy
net_http_start       FAILED with proxy
net_http_get_request FAILED with proxy
net_http_get         FAILED with proxy
open_uri             PASSED with proxy
open_uri             PASSED with no_proxy
http_gem_get         FAILED with proxy
http_gem_via_get     PASSED with proxy
http_gem_via_get     FAILED with no_proxy
faraday_get          PASSED with proxy
faraday_get          FAILED with no_proxy

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment