Browse files

Merge pull request #5 from jankuca/master

Improvements from jankuca. Thanks!
  • Loading branch information...
2 parents e095535 + 166dad0 commit 6c2eafc2266d5ed9de2c21428cd31b4e9a15aaea @gjritter committed Aug 25, 2011
Showing with 30 additions and 9 deletions.
  1. +7 −1 README.md
  2. +1 −0 index.js
  3. +22 −8 lib/nerve.js
View
8 README.md
@@ -70,7 +70,13 @@ The application stores the user's name in the session, so that it can be used in
// and uses sensible defaults if not supplied
res.respond({content: message, headers: {"Content-Type": "text/plain"}});
- }]
+ }],
+
+ ['/abc/:username/:post_id', function (req, res, params) {
+
+ // params = { username: string, post_id: string }
+
+ }]
];
View
1 index.js
@@ -0,0 +1 @@
+module.exports = require('./lib/nerve.js');
View
30 lib/nerve.js
@@ -2,7 +2,7 @@
'use strict';
(function () {
- var sys = require('sys'),
+ var util = require('util'),
http = require('./http_state'),
url = require('url'),
path = require('path'),
@@ -31,7 +31,16 @@
function match_request(matcher, req) {
if (_.isString(matcher)) {
- return (matcher === req.url);
+ var placeholders = matcher.match(/:\w+/g) || [];
+ matcher = matcher.replace(/:\w+/g, '([^/]+)');
+ matcher = new RegExp('^' + matcher + '($|\\?)');
+ var match = req.url.match(matcher);
+ if (!match) return null;
+ var args = {};
+ placeholders.forEach(function (key, i) {
+ args[key.substr(1)] = match[i + 1];
+ });
+ return args;
} else if (_.isRegExp(matcher)) {
return req.url.match(matcher);
} else {
@@ -82,8 +91,8 @@
function exception_response(err) {
return {
- content: '<html><head><title>Exception</title></head><body><h1>Exception</h1><pre>' + sys.inspect(err) + '</pre></body></html>',
- status_code: 501
+ content: '<html><head><title>Exception</title></head><body><h1>Exception</h1><pre>' + err.stack + '</pre></body></html>',
+ status_code: 503
};
}
@@ -96,7 +105,7 @@
var notfile_response = {
content: '<html><head><title>Error</title></head><body><h1>Not a file</h1></body></html>',
- status_code: 501
+ status_code: 404
};
@@ -138,6 +147,8 @@
function request_handler(req, res) {
var handler_match, handler_args = [req, res], pathname;
+ util.log(req.method + ' http://' + req.headers.host + req.url);
+
req.session = req.get_or_create_session(req, res, {
duration: options.session_duration || 30 * 60 * 1000
});
@@ -149,9 +160,12 @@
if (handler_match && handler_match.match) {
try {
- if (_.isFunction(handler_match.match.slice)) {
- handler_args = handler_args.concat(handler_match.match.slice(1));
- }
+ var query = url.parse(req.url, true).query;
+ var params = handler_match.match;
+ Object.keys(params).forEach(function (key) {
+ query[key] = params[key];
+ });
+ handler_args.push(query);
handler_match.handler.apply(null, handler_args);
} catch (e) {
res.respond(exception_response(e));

0 comments on commit 6c2eafc

Please sign in to comment.