Skip to content

Instantly share code, notes, and snippets.

Created Dec 17, 2012
Embed
What would you like to do?
HTTP proxy server (node.js)
// sudo npm install -g http-proxy
// sudo npm install opts
var httpProxy = require('http-proxy'),
url = require('url'),
net = require('net'),
http = require('http'),
opts = require('opts'),
fs = require('fs');
var sys = require('util');
opts.parse([
{
'short': 's',
'description': 'show log',
'value': false,
'required': false
},
{
'short': 'r',
'description': 'routing table file',
'value': true,
'required': false
},
{
'short': 'p',
'description': 'proxy port',
'value': true,
'required': false
}
]);
var proxy_port = opts.get('p') || 7878;
var show_log = opts.get('s');
var routing_table = {};
if(opts.get('r')) {
routing_table = JSON.parse(fs.readFileSync(opts.get('r'), 'utf8'));
}
process.on('uncaughtException', logError);
function truncate(str) {
var maxLength = 256;
return (str.length >= maxLength ? str.substring(0,maxLength) + '...' : str);
}
function logRequest(req) {
console.log(req.method + ' ' + truncate(req.url));
for (var i in req.headers)
console.log(' * ' + i + ': ' + truncate(req.headers[i]));
}
function logError(e) {
console.warn('*** ' + e);
}
var server = httpProxy.createServer(function (req, res, proxy) {
if(show_log)
logRequest(req);
uri = url.parse(req.url);
var host = uri.hostname;
var port = uri.port || 80;
if(routing_table[host]) {
entry = routing_table[host];
host = entry['host'];
port = entry['port'];
}
proxy.proxyRequest(req, res, {
host: host,
port: port
});
});
server.on('upgrade', function(req, socket, head) {
if(show_log)
logRequest(req);
var parts = req.url.split(':', 2);
var conn = net.connect(parts[1], parts[0], function() {
socket.write("HTTP/1.1 200 OK\r\n\r\n");
socket.pipe(conn);
conn.pipe(socket);
});
});
server.listen(proxy_port);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment