Skip to content

Instantly share code, notes, and snippets.

@moschel
Created November 9, 2011 06:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moschel/1350643 to your computer and use it in GitHub Desktop.
Save moschel/1350643 to your computer and use it in GitHub Desktop.
Funcunit proxy
var fs = require('fs'),
path = require('path'),
http = require('http'),
host = '',
port = 80,
localport = 9999
// parse out command line options
process.argv.forEach(function(val) {
if (val.indexOf('--host') == 0) {
host = val.split('=')[1]
} else if (val.indexOf('--port') == 0) {
port = parseInt(val.split('=')[1])
} else if (val.indexOf('--localport') == 0) {
localport = parseInt(val.split('=')[1])
}
})
if (host == '') {
// didn't get a host, so spit out a helpful message
console.log('Usage: node funcunit/proxy.js --host=example.com --port=80 --localport=9999')
process.exit()
}
function serveLocalFile(req, res) {
var url = path.normalize(path.join('.', req.url)).replace(/\?.*$/, "");
if (~url.indexOf('..')) {
// don't send back any files above the directory we were invoked from
res.writeHead(404)
res.end()
} else {
// try to open the file locally
fs.readFile(url, function(err, data) {
if (err) {
res.writeHead(404)
} else {
res.writeHead(200)
res.write(data)
}
res.end()
})
}
}
function proxyToRemote(req, res) {
var proxy = http.createClient(port, host),
preq = proxy.request(req.method, req.url, req.headers)
preq.on('response', function(pres) {
// forward events from the proxy's response back to our client
pres.on('data', function(chunk) {
res.write(chunk, 'binary')
})
pres.on('end', function() {
res.end()
})
// write the proxy's status/headers back to our client
res.writeHead(pres.statusCode, pres.headers)
})
// forward events from our client's request onto the proxy
req.on('data', function(chunk) {
preq.write(chunk, 'binary')
})
req.on('end', function() {
preq.end()
})
}
http.createServer(function(req, res) {
var url = req.url
// anything under these directories will be served locally
if (url.indexOf('/funcunit') == 0 ||
url.indexOf('/steal') == 0 ||
url.indexOf('/test') == 0) {
serveLocalFile(req, res)
} else {
proxyToRemote(req, res)
}
}).listen(localport)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment