Skip to content

Instantly share code, notes, and snippets.

@dodeja
Forked from andrey-kazakov/socksify_faraday.rb
Created August 10, 2016 22:30
Show Gist options
  • Save dodeja/06238bc1d0e595196ac9099fc546cce3 to your computer and use it in GitHub Desktop.
Save dodeja/06238bc1d0e595196ac9099fc546cce3 to your computer and use it in GitHub Desktop.
HTTP over SOCKS support monkey patch for Mechanize, Faraday and it's based clients (OAuth2 like)
# requires socksify gem
require "socksify"
require 'socksify/http'
# use w/ OAuth2 like OAuth2::Client.new(id, secret, connection_opts: { proxy: 'socks://127.0.0.1:9050' })
class Faraday::Adapter::NetHttp
def net_http_class(env)
if proxy = env[:request][:proxy]
if proxy[:uri].scheme == 'socks'
Net::HTTP::SOCKSProxy(proxy[:uri].host, proxy[:uri].port)
else
Net::HTTP::Proxy(proxy[:uri].host, proxy[:uri].port, proxy[:user], proxy[:password])
end
else
Net::HTTP
end
end
end
# requires socksify gem
require "socksify"
require 'socksify/http'
# Mechanize: call @agent.set_socks(addr, port) before using
# any of it's methods; it might be working in other cases,
# but I just didn't tried :)
class Mechanize::HTTP::Agent
public
def set_socks addr, port
set_http unless @http
class << @http
attr_accessor :socks_addr, :socks_port
def http_class
Net::HTTP.SOCKSProxy(socks_addr, socks_port)
end
end
@http.socks_addr = addr
@http.socks_port = port
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment