Skip to content

Instantly share code, notes, and snippets.

@erikdubbelboer
Created September 17, 2012 13:03
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 erikdubbelboer/3737147 to your computer and use it in GitHub Desktop.
Save erikdubbelboer/3737147 to your computer and use it in GitHub Desktop.
Simple http proxy to local VM
/*
TODO:
- add support for https
- add POST support
*/
var http = require('http');
var sep = '-';
http.createServer(function(reqa, resa) {
var myip = reqa.headers.host;
var host = false;
var path = false;
if (reqa.url.indexOf('/' + sep) === 0) {
var s = reqa.url.substr(1).indexOf('/');
host = reqa.url.substr(2, s - 1);
path = reqa.url.substr(s + 1);
} else if (reqa.headers.referer) {
var s = reqa.headers.referer.indexOf('/' + sep);
if (s !== -1) {
var ss = reqa.headers.referer.substr(s + 2);
var s = ss.indexOf('/');
host = ss.substr(0, s);
path = reqa.url;
}
}
if (host === false) {
resa.writeHead(500);
resa.end();
return;
}
delete reqa.headers.host;
delete reqa.headers['accept-encoding']; // Make sure we don't get any encoded files (we can't replace content inside those).
console.log('connecting to: ' + host + ' using url: ' + path);
http.request({
port : 80,
host : host,
method : reqa.method,
path : path,
headers: reqa.headers
}, function(resb) {
resa.writeHead(resb.statusCode, resb.headers);
resb.on('error', function(err) {
console.log(err);
resa.end();
});
resb.on('data', function(chunk) {
if (resb.headers['content-type'] == 'text/html') {
chunk = chunk.toString('ascii')
.replace(/http:\/\//g, 'http://' + myip + '/' + sep);
}
resa.write(chunk);
});
resb.on('end', function() {
resa.end();
});
}).end();
}).listen(8000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment