Ruby HTTP Proxy snippet

Just a small pattern is use all the time for writing HTTP requests that work


with an without a proxy.

#!/usr/bin/env ruby

require 'net/http'

require 'ostruct'



proxy = ENV['http_proxy'] ? URI.parse(ENV['http_proxy']) : OpenStruct.new

Net::HTTP::Proxy(proxy.host,proxy.port,proxy.user,proxy.password).start('www.apple.com') do |http|

  puts http.get('/').body

end

I use here the OpenStruct class which actually works like a more generic Struct where fields can added at will. Comes quite handy since You normally want to have “host”, “port”, “username” and “password” accessors for your proxy URL and Net::HTTP::Proxy is kind enough to accept nil values if they are not required :)

comments powered by Disqus