Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require 'net/http'
require 'rack'
# todo
# - detect ssl
# - keepalive?
module Rack
class Forwarder
def initialize(host, port=80)
@host, @port = host, port
end
def call(env)
rackreq = Rack::Request.new(env)
headers = Rack::Utils::HeaderHash.new
env.each { |key, value|
if key =~ /HTTP_(.*)/
headers[$1] = value
end
}
res = Net::HTTP.start(@host, @port) { |http|
m = rackreq.request_method
case m
when "GET", "HEAD", "DELETE", "OPTIONS", "TRACE"
req = Net::HTTP.const_get(m.capitalize).new(rackreq.fullpath, headers)
when "PUT", "POST"
req = Net::HTTP.const_get(m.capitalize).new(rackreq.fullpath, headers)
req.body_stream = rackreq.body
else
raise "method not supported: #{method}"
end
http.request(req)
}
[res.code, Rack::Utils::HeaderHash.new(res.to_hash), [res.body]]
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment