Last active
August 29, 2015 14:13
-
-
Save ogawatti/dab15417c6a17e9978e2 to your computer and use it in GitHub Desktop.
Mock by ShamRack and Excon
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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