router.js (1325B)
1 var http = require('http'); 2 var url_parse = require('url').parse; 3 4 var routes = {}; 5 6 var methods = ['get', 'put', 'post', 'delete']; 7 8 methods.forEach(function (method) { routes[method] = []; }); 9 10 var addRoute = function (method, pattern, callback) { 11 var regex = new RegExp( 12 '^\/' + 13 pattern.replace(/\//g, '\\\/').replace(/\:\w+/g, '([^\/]+)') + 14 '$' 15 ); 16 // TODO: generate regex from string pattern like Davis 17 routes[method].push({ regex: regex, callback: callback }); 18 }; 19 20 methods.forEach(function (method) { 21 exports[method] = function (pattern, callback) { 22 addRoute(method, pattern, callback); 23 }; 24 }); 25 26 exports.notFound = function (response) { 27 response.writeHead(404); 28 response.end('Not Found\n'); 29 }; 30 31 exports.server = http.createServer(function (request, response) { 32 var method = request.method.toLowerCase(); 33 var path = url_parse(request.url).pathname.replace(/\/$/, ''); 34 var matchingRoutes = routes[method].filter(function (route) { 35 return route.regex.test(path); 36 }); 37 // TODO: handle no matches 404 38 if (matchingRoutes.length == 0) { return exports.notFound(response); } 39 // TODO: handle multiple matches 5** 40 var route = matchingRoutes[0]; 41 var match = path.match(route.regex); 42 match.shift(); 43 route.callback.apply(route.callback, [request, response].concat(match)); 44 });