Created
March 21, 2011 23:53
-
-
Save becojo/880494 to your computer and use it in GitHub Desktop.
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 url = require('url'); | |
var Router = function(){ | |
this.routes = {}; | |
return this; | |
}; | |
Router.prototype.addRoute = function(route){ | |
this.routes[route.name] = route; | |
return this; | |
}; | |
Router.prototype.findRoute = function(verb, path, req){ | |
for(var i in this.routes) if(this.routes[i].verb == verb && this.routes[i].path == path) return this.routes[i].action(req); | |
}; | |
var Route = function(verb, path, action, name){ | |
this.verb = verb || 'get'; | |
this.path = path || '/'; | |
this.name = name || Route.makePathName(path.substr(1)); | |
this.action = action; | |
return this; | |
}; | |
Route.makePathName = function(path){ | |
return path.toLowerCase().split('/').join('_') + '_path'; | |
}; | |
http.createServer(function (req, res) { | |
var App = {Router: new Router()}; | |
App.Router.addRoute({verb: 'get', path: '/', name: 'root_path', action: function(){ return 'Root path'; }}); | |
App.Router.addRoute({verb: 'get', path: '/hello', name: 'hello_path', action: function(){ return 'HEllo path'; }}); | |
res.writeHead(200, {'Content-Type': 'text/plain'}); | |
res.end(App.Router.findRoute(req.method.toLowerCase(), url.parse(req.url, false).pathname, req)); | |
}).listen(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment