Skip to content

Instantly share code, notes, and snippets.

@captainpete
Created June 3, 2010 23:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save captainpete/424693 to your computer and use it in GitHub Desktop.
Save captainpete/424693 to your computer and use it in GitHub Desktop.
// Needs to be run from a separate host that
// does not consider itself the server it's proxying to.
// So ghost the host to a VM running this (as root, for port 80).
var sys = require('sys'),
http = require('http'),
url = require('url');
var port = 80;
var uploaded = 0;
var downloaded = 0;
// Shutdown and exit handlers
process.addListener('exit', function() {
sys.log("Shutting down");
sys.log("Totals\n\tUploaded: " + uploaded + "\n\tDownloaded: " + downloaded);
});
process.addListener('SIGINT', function() {
process.exit();
});
// HTTP proxy
var requestHandler = function(request, response) {
// Parse URL
var uri = url.parse("http://" + request.headers.host + request.url, true);
sys.log(request.method + ": " + uri.host + " " + uri.pathname + " " + JSON.stringify(uri.query || {}));
//sys.log("headers: " + JSON.stringify(request.headers));
// Create proxied request
var pathname = uri.search ? uri.pathname + uri.search : uri.pathname;
var proxiedRequest = http
.createClient(port, uri.host)
.request(request.method, pathname, request.headers);
proxiedRequest.addListener('response', function(proxiedResponse) {
proxiedResponse.addListener('data', function(chunk) {
response.write(chunk);
downloaded += chunk.length;
});
proxiedResponse.addListener('end', function() {
sys.log("Server connection closed, closing client connection");
response.end();
});
sys.log(proxiedResponse.statusCode + ": " + JSON.stringify(proxiedResponse.headers));
response.writeHead(proxiedResponse.statusCode, proxiedResponse.headers);
});
request.addListener('data', function(chunk) {
proxiedRequest.write(chunk);
uploaded += chunk.length;
});
request.addListener('end', function() {
sys.log("Client connection closed, closing server connection");
proxiedRequest.end();
});
};
// Start HTTP proxy
http.createServer(requestHandler).listen(port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment