Created
January 27, 2012 15:51
-
-
Save sandfox/1689400 to your computer and use it in GitHub Desktop.
Simple Nodejs http request 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
var url = require('url'); | |
exports.getRouter = function getRouter() | |
{ | |
var routes = []; | |
function addRoute(method, path, callback) | |
{ | |
var route = { | |
method : method, | |
path : path, | |
callback : callback | |
} | |
routes.push(route); | |
} | |
function get(path, handler) { | |
return addRoute("GET", path, handler); | |
} | |
function post(path, handler) { | |
return addRoute("POST", path, handler); | |
} | |
function put(path, handler) { | |
return addRoute("PUT", path, handler); | |
} | |
function del(path, handler) { | |
return addRoute("DELETE", path, handler); | |
} | |
function head(path, handler) { | |
return addRoute("HEAD", path, handler); | |
} | |
function routeRequest(request, response) | |
{ | |
var pathname = url.parse(request.url).pathname | |
for (var i = 0, l = routes.length; i < l; i += 1) { | |
var route = routes[i]; | |
if (request.method === route.method && pathname.lastIndexOf(route.path, 0) === 0) { | |
route.callback(request, response) | |
} | |
} | |
} | |
return { | |
get : get, | |
post: post, | |
put: put, | |
del: del, | |
routeRequest: routeRequest | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment