Created
April 8, 2011 19:15
-
-
Save sintaxi/910529 to your computer and use it in GitHub Desktop.
a simple reverse proxy using Node
This file contains 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
var http = require("http"), | |
util = require("util") | |
http.createServer(function(req, rsp){ | |
var regex = /^\/(v1|v2)/g | |
var matches = req.url.match(regex) | |
if((matches && matches[0] === "/v1") || (req.headers["x-api-version"] === "v1")) | |
var port = 8001 | |
if((matches && matches[0] === "/v2") || (req.headers["x-api-version"] === "v2")) | |
var port = 8002 | |
var url = req.url.replace(regex, "") | |
if(port){ | |
var options = { | |
host: 'localhost', | |
port: port, | |
path: url, | |
method: req.method, | |
headers: req.headers | |
} | |
proxy = http.request(options, function(response){ | |
rsp.writeHead(response.statusCode, response.headers) | |
response.on("data",function(chunk){ | |
rsp.write(chunk) | |
}) | |
response.on("end", function(){ | |
rsp.end() | |
}) | |
}) | |
proxy.once("error", function(){ }) | |
util.pump(req, proxy) | |
req.on('end', function () { | |
proxy.end() | |
}) | |
}else{ | |
var body = "Please specify a version.\n" | |
rsp.writeHead(303,{ | |
"Content-Length": body.length, | |
"Location": "/v1" + req.url | |
}) | |
rsp.end(body) | |
} | |
}).listen(8000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment