Skip to content

Instantly share code, notes, and snippets.

Created November 15, 2013 14:18
Show Gist options
  • Save anonymous/7485006 to your computer and use it in GitHub Desktop.
Save anonymous/7485006 to your computer and use it in GitHub Desktop.
This node.js "server" is my "make very URL I've ever made still work" add on to my own https://github.com/thepatrick/frontendserver http router.
var http = require('http');
http.createServer(function(req, res){
function giveup(code) {
if(code == 410) {
res.writeHead(410, {
Server: "pfe+redirect",
"X-Patrick-Says": "Redirect Engine in just 41 lines of code. node.js rocks"
});
res.end("This content is gone, there is no forwarding address. Sorry.");
} else {
res.writeHead(302, {
Location: "http://thepatrick.com.au/",
Server: "pfe/redirect",
"X-Patrick-Says": "Redirect Engine in just 41 lines of code. node.js rocks"
});
res.end("Redirecting to http://thepatrick.com.au/");
}
}
function re(url, m, destUrl, status) {
if(_ref = url.match(new RegExp(m))) {
for(var idx = 1; idx < _ref.length; idx++) {
destUrl = destUrl.replace("$" + idx, _ref[idx]);
}
if(status == 410) {
giveup(410);
} else {
res.writeHead(status || 302, {
Location: destUrl,
Server: "pfe/redirect",
"X-Patrick-Says": "Redirect Engine in just 41 lines of code. node.js rocks"
});
res.end();
}
return true;
}
return false;
}
// frontendserver rewrites URLs like "http://soapbox.co.nz/somewhere" to "http://127.0.0.1:10394/soapbox/somewhere"
if(req.url.substring(0, 15) == "/patrickgeeknz/") {
patrickgeeknz(re.bind(null, req.url.substring(15)), giveup);
} else if(req.url.substring(0, 9) == "/soapbox/") {
soapbox(re.bind(null, req.url.substring(9)), function() {
patrickgeeknz(re.bind(null, req.url.substring(9)), giveup);
});
} else {
giveup();
}
}).listen(10394, function() {
console.log("Up and running on http://localhost:10394/ ...");
});
function soapbox(re, giveup) {
// Either 301 (permanent) and 302 (temporary) HTTP status codes are supported
if(re("^bar"), 302)) return;
if(re("^bam"), 301)) return;
// Simple substituion is supported
if(re("^past/([0-9]{4})/([0-9]{1,2})[/]?([0-9]{1,2})?[/]?$", "http://myio.com.au/archive/$1/$2/", 301)) return;
// 410 (and no forwarding URL, obviously) and it'll send a 410 gone instead
if(re("^gone", null, 410)) return;
// If none of our rules match we giveup(),
// which in this case tries the patrickgeeknz() set below
giveup();
}
function patrickgeeknz(re, giveup) {
// Send the default thing away
if(re("^$", "http://thepatrick.com.au/", 301)) return;
giveup();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment