Created
February 24, 2014 09:39
-
-
Save jameswomack/9184636 to your computer and use it in GitHub Desktop.
Matching routes in a base node.js HTTP 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
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