router.js (1538B)
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 if (!(pattern instanceof RegExp)) { 12 pattern = new RegExp( 13 '^\/' + pattern.replace(/\//g, '\\\/').replace(/\:\w+/g, '([^\/]+)') + '$' 14 ); 15 } 16 // TODO: generate regex from string pattern like Davis 17 routes[method].push({ regex: pattern, 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 console.log(method + ': ' + path); 35 var matchingRoutes = routes[method] || []; 36 matchingRoutes = matchingRoutes.filter(function (route) { 37 return route.regex.test(path); 38 }); 39 if (path == '' && exports.index) { 40 matchingRoutes = [ { callback: exports.index } ]; 41 } 42 // TODO: handle no matches 404 43 if (matchingRoutes.length == 0) { return exports.notFound(response); } 44 // TODO: handle multiple matches 5** 45 var route = matchingRoutes[0]; 46 var match = path.match(route.regex); 47 match.shift(); 48 route.callback.apply(route.callback, [request, response].concat(match)); 49 });