var http = require('http');
var url = require('url');
var winston = require('winston');
var logger = new (winston.Logger)({
transports: [
new (winston.transports.Console)(),
new (winston.transports.File)({ filename: 'proxy.log', json: false })
]
});
var base_url;
http.createServer(function (clientRequest, clientResponse) {
logger.info('ENTERING createServer');
function makeProxyRequest(clientRequestUrl) {
logger.info('ENTERING makeProxyRequest');
// hack!
clientRequestUrl.protocol = 'http:';
if (typeof(clientRequestUrl.hostname) === "undefined") {
clientRequestUrl.hostname = base_url.hostname;
}
logger.info('client url: ' + url.format(clientRequestUrl));
proxy = http.request(clientRequestUrl, proxyResponseHandler);
proxy.on('error', function(e) {
logger.error('problem with proxy request to '
+ clientRequestUrl.host + '/' + clientRequestUrl.path
+ ': ' + JSON.stringify(e));
clientResponse.end();
});
proxy.end();
logger.info('EXITING makeProxyRequest');
}
function proxyResponseHandler(proxyResponse) {
logger.info('ENTERING proxyResponseHandler');
logger.info('status: ' + proxyResponse.statusCode);
switch(proxyResponse.statusCode) {
case 301:
case 302:
var new_url = url.parse(proxyResponse.headers['location']);
if(typeof(new_url.host) !== 'undefined') {
base_url = new_url;
}
logger.info('redirect received: ' + JSON.stringify(new_url));
makeProxyRequest(new_url);
break;
case 200:
for(header in proxyResponse.headers) {
logger.info(' ' + header + ': ' + proxyResponse.headers[header]);
clientResponse.setHeader(header, proxyResponse.headers[header]);
}
clientResponse.writeHead(proxyResponse.statusCode);
proxyResponse.on('data', function(data) {
clientResponse.write(data);
});
proxyResponse.on('end', function() {
logger.info('end from origin');
clientResponse.end();
});
break;
}
logger.info('EXITING proxyResponseHandler');
}
//////////////////////// Execution starts here //////////////////////////////
var tmp_url = url.parse(clientRequest.url.substring(1));
logger.info(JSON.stringify(tmp_url));
logger.info(tmp_url.host);
if (typeof(tmp_url.host) !== 'undefined' && typeof(base_url) === 'undefined' ) {
base_url = tmp_url;
}
makeProxyRequest(tmp_url);
logger.info('EXITING createServer');
}).listen(8124);
console.log('Server running at http://127.0.0.1:8124/');