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']) :

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

  puts http.get('/').body


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 :)