Skip to content

Instantly share code, notes, and snippets.

@leahneukirchen
Created December 5, 2008 16:04
Show Gist options
  • Save leahneukirchen/32376 to your computer and use it in GitHub Desktop.
Save leahneukirchen/32376 to your computer and use it in GitHub Desktop.
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