Created
April 19, 2010 12:56
-
-
Save simonw/371013 to your computer and use it in GitHub Desktop.
A reverse proxy in Node - GET only at the moment
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // node-reverse-proxy | |
| var sys = require('sys'), | |
| http = require('http'); | |
| function proxy(backend, request, response) { | |
| var bits = backend.split(':'); | |
| var host = bits[0]; | |
| if (bits.length == 2) { | |
| var port = parseInt(bits[1], 10); | |
| } else { | |
| var port = 80; | |
| } | |
| request.setEncoding('binary'); | |
| var method = request.method; | |
| var path = request.url; // e.g. /status?name=ryan | |
| var client = http.createClient(port, host); | |
| var httprequest = client.request(method, path, {'host': host}); | |
| httprequest.addListener('response', function(httpresponse) { | |
| var statusCode = httpresponse.statusCode; | |
| var headers = httpresponse.headers; | |
| httpresponse.setEncoding('binary'); | |
| var body = ''; | |
| httpresponse.addListener('data', function(chunk) { | |
| body += chunk; | |
| }); | |
| httpresponse.addListener('end', function() { | |
| response.writeHead(statusCode, headers); | |
| response.write(body, 'binary'); | |
| response.end(); | |
| }); | |
| }); | |
| httprequest.end(); | |
| } | |
| http.createServer(function (req, res) { | |
| proxy('localhost', req, res); | |
| }).listen(8001); | |
| sys.puts('Server running at http://127.0.0.1:8001/'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment