Skip to content

Instantly share code, notes, and snippets.

@bouzuya
Created January 31, 2016 05:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bouzuya/142dabfb5eed4e2a35cc to your computer and use it in GitHub Desktop.
Save bouzuya/142dabfb5eed4e2a35cc to your computer and use it in GitHub Desktop.
path-to-regexp example
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();
@bouzuya
Copy link
Author

bouzuya commented Jan 31, 2016

$ npm i express path-to-regexp
$ node server.js
$ curl http://localhost:3000/entries
entry list html

$ curl http://localhost:3000/entries/123
entry item html : 123

$ curl http://localhost:3000/foo        
not found

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment