Created
January 3, 2012 21:23
-
-
Save edwardhotchkiss/1557002 to your computer and use it in GitHub Desktop.
NodeJS minimal `sintra` style router
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
/** | |
* Node.JS Sinatra Style Routing | |
*/ | |
var routes = {} | |
, http = require('http') | |
, parse = require('url').parse | |
, server = http.createServer(); | |
/** | |
* @class http.ServerResponse | |
* @method send | |
* @param {Object/String} message Data to send | |
* @optional {Number} code HTTP Status Code | |
* @optionsal {String} type Content-Type | |
*/ | |
http.ServerResponse.prototype.send = function(message, code, type) { | |
code = code || 200; | |
type = type || 'text/html'; | |
if (/object/.test(typeof(message))) { | |
message = JSON.stringify(message); | |
type = 'application/json'; | |
}; | |
this.writeHead(code, { 'Content-Type': type }); | |
this.end(message); | |
}; | |
/** | |
* @method addRoute | |
* @param {String} path URL endpoint | |
* @param {String} method HTTP Method | |
* @param {Function} fn Callback function | |
*/ | |
function addRoute(path, method, fn) { | |
routes[path] = {}; | |
routes[path][method] = fn; | |
}; | |
/** | |
* @method route | |
* @param {Object} request HTTP Request object | |
* @param {Object} response HTTP Response object | |
*/ | |
function route(request, response) { | |
var pathname = parse(request.url).pathname; | |
if (routes[pathname] && routes[pathname][request.method]) { | |
var handle = routes[pathname][request.method]; | |
handle.apply(this, arguments); | |
} else { | |
}; | |
}; | |
['GET','PUT','POST','DELETE'].forEach(function(method) { | |
http.Server.prototype[method.toLowerCase()] = function(path, callback) { | |
addRoute(path, method, callback); | |
} | |
}); | |
server.on('request', function theHandler(request, response) { | |
route(request, response); | |
}); | |
/** | |
* Demo | |
*/ | |
server.get('/', function(request, response) { | |
response.send({ message : 'routed, son'}); | |
}); | |
server.get('/routes', function(request, response) { | |
response.send(routes); | |
}); | |
server.listen(8000); | |
/* EOF */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment