Add support for file based url list

parent 30ef9e4f
......@@ -4,33 +4,61 @@
// an example of how to write a middleware.
//
function matcher (url, dest) {
// First, turn the URL into a regex.
// NOTE: Turning user input directly into a Regular Expression is NOT SAFE.
var r = new RegExp(url.replace(/\//, '\\/'));
// This next block of code may look a little confusing.
// It returns a closure (anonymous function) for each URL to be matched,
// storing them in an array - on each request, if the URL matches one that has
// a function stored for it, the function will be called.
return function (url) {
var m = url.match(r);
if (!m) {
return;
}
var path = url.slice(m[0].length);
console.log('proxy:', url, '->', dest);
return {url: path, dest: dest};
var fs = require('fs');
function getMatchers(urls) {
var matchers = [],
matcher,
url,
r;
for (url in urls) {
// Call the 'matcher' function above, and store the resulting closure.
// First, turn the URL into a regex.
// NOTE: Turning user input directly into a Regular Expression is NOT SAFE.
r = new RegExp(url.replace(/\//, '\\/'));
// This next block of code may look a little confusing.
// It returns a closure (anonymous function) for each URL to be matched,
// storing them in an array - on each request, if the URL matches one that has
// a function stored for it, the function will be called.
matcher = (function(r) {
var dest = urls[url];
return function (url) {
var m = url.match(r);
if (!m) {
return;
}
var path = url.slice(m[0].length);
console.log('proxy:', url, '->', dest);
return ({url: path, dest: dest});
}})(r);
matchers.push(matcher);
}
return matchers;
}
module.exports = function (urls) {
// This is the entry point for our middleware.
// 'matchers' is the array of URL matchers, as mentioned above.
var matchers = [];
for (var url in urls) {
// Call the 'matcher' function above, and store the resulting closure.
matchers.push(matcher(url, urls[url]));
var matchers,
urlFile;
if (typeof urls === 'string') {
//
// If we are passed a string then assume it is a
// file path, parse that file and watch it for changes
//
urlsFile = urls,
urls = JSON.parse(fs.readFileSync(urlsFile));
fs.watchFile(urlsFile, function () {
console.log("Reloading urls...");
fs.readFile(urlsFile, function (err, data) {
if (err) {
self.emit('error', err);
}
urls = JSON.parse(data);
matchers = getMatchers(urls);
});
});
}
matchers = getMatchers(urls);
// This closure is returned as the request handler.
middleware = function (req, res, next) {
......@@ -61,6 +89,7 @@ module.exports = function (urls) {
//
// Same as above, but for WebSocket
//
console.log("Websocket proxying : " + req.url);
var proxy = next;
for (var k in matchers) {
// for each URL matcher, try the request's URL.
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment