Skip to content

Instantly share code, notes, and snippets.

@jameswomack
Created February 24, 2014 09:39
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 jameswomack/9184636 to your computer and use it in GitHub Desktop.
Save jameswomack/9184636 to your computer and use it in GitHub Desktop.
Matching routes in a base node.js HTTP server
var http = require('http');
var routes = {
'/foo/.*' : function (req, res) {
res.locals.content = res.locals.content + '<h1>Foo Bar</h1>';
},
'/foo' : function (req, res) {
res.locals.content = res.locals.content + '<h1>Foo</h1>';
}
};
function match(req, res) {
var keys = Object.keys(routes);
for (var i = 0; i < keys.length; i++) {
if (req.url.match(keys[i])) {
routes[keys[i]](req, res);
}
}
}
http.createServer(function (req, res) {
res.locals = {content: ''};
res.writeHead(200, {'Content-Type': 'text/html'});
match(req, res);
res.end(res.locals.content );
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment