Skip to content

Instantly share code, notes, and snippets.

@booo
Created June 4, 2012 01:19
Show Gist options
  • Select an option

  • Save booo/2865751 to your computer and use it in GitHub Desktop.

Select an option

Save booo/2865751 to your computer and use it in GitHub Desktop.
http forker
# fork http traffic
# e.g. proxy is your production system
# and proxy2 your testing setup
http = require "http"
PRODUCTION_HOST = "localhost"
PRODUCTION_PORT = 8081
TESTING_HOST = "localhost"
TESTING_PORT = 8082
SERVER_HOST = "localhost"
SERVER_PORT = 8080
http.globalAgent.maxSockets = 500
server = http.createServer (req, res) ->
# stolen from node-http-proxy source
if req.headers["x-forwarded-for"]
req.headers["x-forwarded-for"] += "," + req.connection.remoteAddress || req.socket.remoteAddress
else
req.headers["x-forwarded-for"] = req.connection.remoteAddress || req.socket.remoteAddress
if req.headers["x-forwarded-port"]
req.headers["x-forwarded-port"] += "," + req.connection.remotePort || req.socket.remoteAddress
else
req.headers["x-forwarded-port"] = req.connection.remotePort || req.socket.remoteAddress
options =
host: PRODUCTION_HOST
port: PRODUCTION_PORT
path: req.url
method: req.method
headers: req.headers
proxyRequest = http.request options, (response) ->
response.on "data", (data) -> res.write data #, "binary"
response.once "end", -> res.end()
response.headers.connection = "close" #TODO ???
res.writeHead response.statusCode, response.headers
options.port = TESTING_PORT
options.host = TESTING_HOST
proxyRequest2 = http.request options
proxyRequest.once "error", (error) -> console.log error
proxyRequest2.once "error", (error) -> console.log error
# handle data from client to proxy
# forward data to upstream servers
req.on "data", (data) ->
try
proxyRequest.write data #, "binary"
catch e
console.log e
try
proxyRequest2.write data
catch e
console.log e
# handle end event from client
# end request of upstream servers
req.once "end", ->
try
proxyRequest.end()
catch e
console.log e
try
proxyRequest2.end()
catch e
console.log e
server.listen SERVER_PORT, SERVER_HOST
(http.createServer (req, res) ->
#console.log "Request on production system #{req.method} #{req.url}"
#console.log ("#{key}: #{value}" for key, value of req.headers).join "\n"
res.writeHead 200
res.end()
).listen PRODUCTION_PORT, PRODUCTION_HOST
(http.createServer (req, res) ->
#console.log "Request on testing system #{req.method} #{req.url}"
#console.log ("#{key}: #{value}" for key, value of req.headers).join "\n"
res.writeHead 200
res.end()
).listen TESTING_PORT, TESTING_HOST
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment