Skip to content

Instantly share code, notes, and snippets.

@becojo
Created March 21, 2011 23:53
Show Gist options
  • Save becojo/880494 to your computer and use it in GitHub Desktop.
Save becojo/880494 to your computer and use it in GitHub Desktop.
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