node.jsの練習

簡単なhttp proxyを書いてみた。

var http = require('http');

http.createServer(function (req, res) {
	var proxy_headers = req.headers,
		proxy_req,
		client;

	function _client(host) {
		var h, _host, _port;
		if(host.indexOf(':') > 0){
			h = host.split(':');
			_host = h[0];
			_port = parseInt(h[1],10);
		} else {
			_host = host;
			_port = 80;
		}
		return http.createClient( _port, _host  );
	}

	function _proxy_response(proxy_res) {
		var headers = proxy_res.headers;
		res.writeHead(proxy_res.statusCode, headers);
		proxy_res.on('data', function(chunk) { res.write(chunk); });
		proxy_res.on('end', function() { res.end(); });	
	}

	client = _client(proxy_headers.host);

	if (req.method === 'GET'){
		proxy_req = client.request(req.method, req.url, proxy_headers);
		proxy_req.end();
		proxy_req.on('response', _proxy_response);
	} else if(req.method === 'POST'){
		proxy_req = client.request(req.method, req.url, proxy_headers);
		req.on('data',function(chunk){ proxy_req.write(chunk); });
		req.on('end',function(){
			proxy_req.end();
			proxy_req.on('response',  _proxy_response);
		});
	}

}).listen(8080, "localhost");