Skip to content

Instantly share code, notes, and snippets.

@ogawatti
Last active August 29, 2015 14:13
Show Gist options
  • Save ogawatti/dab15417c6a17e9978e2 to your computer and use it in GitHub Desktop.
Save ogawatti/dab15417c6a17e9978e2 to your computer and use it in GitHub Desktop.
Mock by ShamRack and Excon
require 'net/http'
require 'sham_rack'
require 'excon'
class Middleware
def initialize(app)
@app = app
end
def call(env)
if env["REQUEST_METHOD"] == "GET" && env["PATH_INFO"] == "/"
["200 OK", { "Content-type" => "text/plain" }, ["Hello, world!"]]
else
@app.call(env)
end
end
end
rackapp = Proc.new do |env|
request = Rack::Request.new(env)
proxy = "http://#{ENV['PROXY_USER']}:#{ENV['PROXY_PASS']}@#{ENV['PROXY_HOST']}:#{ENV['PROXY_PORT']}"
res = Excon.get(request.url, :proxy => proxy)
[ res.status, res.headers, [ res.body ] ]
end
app = Middleware.new(rackapp)
ShamRack.at("www.google.co.jp") do |env|
app.call(env)
end
def get(url)
uri = URI.parse(url)
http = Net::HTTP::Proxy(
ENV['PROXY_HOST'], ENV['PROXY_PORT'], ENV['PROXY_USER'], ENV['PROXY_PASS']
).new(uri.host, uri.port)
http.use_ssl = true if uri.scheme == "https"
http.get(uri.path)
end
res = get("http://www.google.co.jp/")
p res.code #=> "200"
p res.body #=> "Hello, world!"
res = get("http://www.google.co.jp/webhp")
p res.code #=> "200"
p res.body #=> "<!doctype html><html itemscop..."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment