Skip to content

Instantly share code, notes, and snippets.

@hokaccha
Created November 10, 2011 10:58
Show Gist options
  • Save hokaccha/1354601 to your computer and use it in GitHub Desktop.
Save hokaccha/1354601 to your computer and use it in GitHub Desktop.
express mapRouter
var express = require('express')
, mapRouter = require('./express-mapRouter')
, app = express.createServer()
, routesDir = __dirname + '/routes';
// 'GET /' : 'root:index' はこれと同じ
// var root = require('./routes/root');
// app.get('/', root.index);
var routesMap = {
'GET /' : 'root:index'
, 'GET /about' : 'about:index'
, 'GET /entry' : 'entry:index'
, 'POST /entry' : 'entry:create'
};
app.mapRouter(routesMap, routesDir);
app.listen(3000);
var express = require('express');
express.HTTPServer.prototype.mapRouter =
express.HTTPSServer.prototype.mapRouter = function(routesMap, routesDir) {
var app = this;
Object.keys(routesMap).forEach(function(key) {
var val = routesMap[key];
var _key = key.split(/\s+/);
var _val = val.split(/:/);
var method = _key[0].toLowerCase();
var path = _key[1];
var routesFile = _val[0];
var routesFunc = _val[1];
var routesFuncs = require(routesDir + '/' + routesFile);
app[method](path, routesFuncs[routesFunc]);
});
};
// routes/about.js
var about = module.exports;
about.index = function about_index(req, res) {
res.send('about/index');
};
// routes/entry.js
var entry = module.exports;
entry.index = function entry_index(req, res) {
res.send('entry/index');
};
entry.create = function entry_create(req, res) {
res.send('entry/create');
};
// routes/root.js
var root = module.exports;
root.index = function root_index(req, res) {
res.send('root/index');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment