Skip to content

Instantly share code, notes, and snippets.

@romgerman
Last active May 5, 2017 09:05
Show Gist options
  • Select an option

  • Save romgerman/4ce5a72bddd982ff1f7c9f22eb5b63df to your computer and use it in GitHub Desktop.

Select an option

Save romgerman/4ce5a72bddd982ff1f7c9f22eb5b63df to your computer and use it in GitHub Desktop.
Simple node.js router
function Router () {
this.routes = [];
this.fallback = function(request, response) { };
this.run = function (request, response) {
var pathname = url.parse(request.url).pathname;
var match = this.routes.map(function(route) {
var routeUrl = route.url;
var requestUrl = pathname.split('/');
if ((!route.wildcard && requestUrl.length !== routeUrl.length) ||
(route.wildcard && requestUrl.length < routeUrl.length))
return null;
var args = [];
var wildcard = null;
var length = route.wildcard ? requestUrl.length : routeUrl.length;
for(var i = 0; i < length; i++) {
if (wildcard !== null) {
wildcard.push(requestUrl[i]);
} else {
if (routeUrl[i].startsWith(':')) {
if (routeUrl[i].endsWith('+')) {
wildcard = [];
wildcard.push(requestUrl[i]);
} else {
args.push(requestUrl[i]);
}
} else if (routeUrl[i] !== requestUrl[i]) {
return null;
}
}
}
if (wildcard) args.push(wildcard);
return { route, args };
}).filter(i => { return i != null; })[0];
if (match) {
match.route.callback.apply(null, [request, response].concat(match.args));
} else {
this.fallback(request, response);
}
}
this.get = function (url, callback) {
if (typeof url === 'function') {
this.fallback = url;
return;
}
var parts = url.split('/');
var wild = parts[parts.length - 1].startsWith(':') && parts[parts.length - 1].endsWith('+');
this.routes.push({ url: parts, callback, wildcard: wild });
}
}
var router = new Router();
// Ex.- localhost/sample/some_id/dick_wolf
router.get('/sample/:id/:name', function(request, response, id, name) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('This is sample [' + id + ', ' + name + ']');
});
router.get('/sample', function(request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('This is just a simple sample');
});
// Route with wildcard param in the end. "name" arg will be an array
router.get('/get/:name+', function(request, response, name) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Yes, ' + name);
});
// Calls if there is no routes matches current path
router.get(function(request, response) {
response.writeHead(404, {'Content-Type': 'text/plain'});
response.end('[404] Not found');
});
http.createServer(function(request, response) {
router.run(request, response);
}).listen(80);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment