Skip to content

Instantly share code, notes, and snippets.

@yorickvP
Created May 18, 2012 15:15
Show Gist options
  • Save yorickvP/2725801 to your computer and use it in GitHub Desktop.
Save yorickvP/2725801 to your computer and use it in GitHub Desktop.
Simple (regex) routing in JavaScript
module.exports = function router() {
function router(method, url) {
var r = get_routes(method), rl = r.length
for (var i = 0; i < rl; ++i) {
if (r[i].type == 'string') {
if (r[i].url == url)
return [[url], r[i].callback] }
else {
var route = r[i]
if (route.type == 'regexp') {
var match = route.url.exec(url)
if (match)
return [match, route.callback] }
else throw TypeError("unknown routing url type") }}
return null }
var routes = { get: [], post: []}
var get_routes = function(method) { return routes[method] || (routes[method] = []) }
router.set = function(method, url, callback) {
get_routes(method).push(
{ url: url
, callback: callback
, type: Object.prototype.toString.call(url).slice(8,-1).toLowerCase() })
return router }
router.get = function(url, callback) {
router.set('get', url, callback)
router.set('head', url, callback)
return router }
router.post = function(url, callback) {
router.set('post', url, callback)
return router }
return router }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment