Created
February 14, 2014 01:51
-
-
Save justinabrahms/8994424 to your computer and use it in GitHub Desktop.
A simple HTTP proxy for speedy static file serving, sending dynamic requests to a backend web server.
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
/** | |
* A proxy for loading static files in development. Django doesn't handle this well. | |
* | |
* To run, do something like: | |
* npm install . | |
* node proxy.js --docroot=$PWD | |
* | |
* Then just visit http://localhost:9000/ as you normally would. | |
*/ | |
var httpProxy = require('http-proxy'); | |
var http = require('http'); | |
var url = require('url'); | |
var fs = require('fs'); | |
var mime = require('mime'); | |
var argv = require('optimist') | |
.usage('Usage: $0 --port=[port] --server=[backing_server_url] --docroot=[repo_dir]') | |
.string(['docroot']) | |
.demand(['docroot']) | |
.argv; | |
var port = argv.port || 9000; | |
var proxy = httpProxy.createProxyServer(); | |
var isStatic = new RegExp(/\/static\/(.*)/); | |
var server = http.createServer(function (req, res) { | |
var u = url.parse(req.url); | |
var match = isStatic.exec(u.pathname) | |
if (match) { | |
console.log('loading file at html/static/' + match[1]); | |
var path = argv.docroot + '/html/static/' + match[1]; | |
fs.exists(path, function (exists) { | |
if (exists) { | |
res.setHeader('Content-Type', mime.lookup(path)); | |
fs.createReadStream(path, 'utf8').pipe(res); | |
} else { | |
res.statusCode = 404; | |
res.end(); | |
} | |
}); | |
} else { | |
proxy.web(req, res, { | |
target: (argv.backing_server || "http://localhost:8000") | |
}); | |
} | |
}); | |
console.log('listening at port http://localhost:' + port + '/'); | |
server.listen(port); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment