Created
January 31, 2016 05:31
-
-
Save bouzuya/142dabfb5eed4e2a35cc to your computer and use it in GitHub Desktop.
path-to-regexp example
This file contains hidden or 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 express = require('express'); | |
var pathToRegexp = require('path-to-regexp'); | |
var entriesIndex = function() { | |
return 'entry list html'; | |
}; | |
var entriesShow = function(params) { | |
return 'entry item html : ' + params[0]; | |
}; | |
var notFound = function() { | |
return 'not found'; | |
}; | |
var getRoutes = function() { | |
return [ | |
['/entries', entriesIndex], | |
['/entries/:id', entriesShow], | |
['*', notFound] | |
].map(function(route) { | |
return { | |
re: pathToRegexp(route[0]), | |
handler: route[1] | |
}; | |
}); | |
} | |
var render = function(routes, path) { | |
for (var i = 0; i < routes.length; i++) { | |
var route = routes[i]; | |
var match = route.re.exec(path); | |
if (match) return route.handler(match.slice(1)); | |
} | |
return null; | |
}; | |
var main = function() { | |
var routes = getRoutes(); | |
var app = express(); | |
app.get('*', function(req, res) { | |
res.send(render(routes, req.path)); | |
}); | |
app.listen(3000); | |
}; | |
main(); |
Author
bouzuya
commented
Jan 31, 2016
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment