Skip to content

Instantly share code, notes, and snippets.

@zh
Forked from sintaxi/server.js
Created April 13, 2011 08:16
Show Gist options
  • Save zh/917180 to your computer and use it in GitHub Desktop.
Save zh/917180 to your computer and use it in GitHub Desktop.
simple reverse proxy with node.js
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){
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)
@robertne13
Copy link

anyway to create udp reverse proxy too?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment