Created
July 11, 2012 02:58
-
-
Save jasonwyatt/3087698 to your computer and use it in GitHub Desktop.
Node.js server which will bounce requests to other servers.
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
/** | |
* bounceserver.js | |
* License: MIT (http://www.opensource.org/licenses/mit-license.php/) | |
* Author: Jason Feinstein (jason.feinstein@gmail.com) | |
* | |
* Instructions: | |
* 1. Install node.js: http://nodejs.org | |
* 2. run this file, listing the bounce addresses like so: | |
* node bounceserver.js http://mybounceaddress:1111/ http://google.com | |
* 3. Start sending requests to the server. They will be bounced properly! | |
*/ | |
var http = require('http'); | |
var url = require('url'); | |
// Collect the destinations. | |
var destinations = process.argv.slice(2); | |
destinations.forEach(function(val, index, array){ | |
destinations[index] = url.parse(val); | |
}); | |
// Create the server. | |
var server = http.createServer(function (req, res) { | |
var body = "", | |
requestID = (new Date()).getTime(); | |
// Collect data from the request. | |
req.on('data', function (chunk) { | |
body += chunk; | |
}); | |
// When the request is finished, pipe it to the destinations. | |
req.on('end', function (){ | |
console.log(new Date() + ": Request "+requestID+" Received."); | |
// Always return 200 (good idea?) | |
res.writeHead(200); | |
// For each destination, make a request to the destinations. | |
for (var i = 0, len = destinations.length; i < len; i++) { | |
(function(destination){ | |
var bounceRequest = http.request({ | |
hostname: destination.hostname, | |
port: destination.port, | |
path: destination.path, | |
headers: req.headers, | |
auth: req.auth, | |
method: req.method | |
}, function(bounceRes) { | |
console.log(new Date() + ": Request "+requestID+"'s' Bounce to "+destination.hostname+" Finished With "+bounceRes.statusCode); | |
} | |
); | |
bounceRequest.write(body); | |
bounceRequest.end(); | |
})(destinations[i]); | |
} | |
// Simple response content. | |
res.end(""); | |
}); | |
}); | |
var port = 1337, | |
address = '0.0.0.0'; // same as 127.0.0.1, but available outside | |
// start the server | |
server.listen(port, address); | |
// inform users | |
console.log("Server listening on "+address+":"+port+", bouncing to: ", destinations.map(function(obj){return obj.href})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment