reorx
7/7/2012 - 1:16 AM

Gravator Proxy

Gravator Proxy

/*
*@fileOverview gravator proxy
* reuqire node.js v0.6.7
*/
if(process.argv.length>1&&process.argv[2]=='-d'){
	var HOST = '127.0.0.1';
	var PORT = 1337;
}
var HOST = HOST||'0.0.0.0';
var PORT = PORT||80;

var http = require('http');
var fs = require('fs');

http.createServer(function (req, res) {
    if(req.url.search('/avatar') == 0){
	    var options = {
            host: 'www.gravatar.com',
            port: 80,
            path: req.url
    	};
        http.get(options, function(res2) {
            if(200 == res2.statusCode){
                res.setHeader("Content-Type", "image/png");
                
                res2.setEncoding('binary');
                res2.on('data', function (chunk) {
                    res.write(chunk, 'binary');
                });
                res2.on('end', function (chunk) {
                    res.end();
                });
            }else{
                res.writeHead(res2.statusCode,res2.headers);
                res.end();
            }
    	}).on('error', function(e) {
    	    res.end("Got error: " + e.message);
    	});
	}else{
	    var html = '<html>'+
            '<head>'+
            '<meta http-equiv="Content-Type" content="text/html; '+
            'charset=UTF-8" />'+
            '<title>Hello World!</title>'+
            '</head>'+
            '<body>'+
            '<div>'+
            '<p>Hello World!</p>'+
            '<p>/avatar/{gravatar_id}?s=48</p>'+
            '<p>for example: /avatar/767fc9c115a1b989744c755db47feb60?size=48</p> <img src="/avatar/767fc9c115a1b989744c755db47feb60?size=48"/>'+
            '</div>'+
            '</body>'+
            '</html>';
	    res.end(html);
	}		
}).listen(PORT, HOST);
console.log('Server running at http://'+HOST+':'+PORT+'/');