Skip to content

Instantly share code, notes, and snippets.

@sinefunc
Created August 2, 2010 02:33
Show Gist options
  • Save sinefunc/504038 to your computer and use it in GitHub Desktop.
Save sinefunc/504038 to your computer and use it in GitHub Desktop.
var nodenatra = require('./nodenatra');
app = new nodenatra.App();
app.get('/', function() {
return "Hello";
});
app.get('/posts', function() {
return "Hey there!";
});
app.get('/post/:id', function (id) {
if (id == 2) { return 404; }
return "Hey there post #" + id;
});
app.run();
// Hacked together as a demo :) -- for production work, consider
// using ExpressJS instead. (expressjs.com)
var http = require('http'),
sys = require('sys'),
url = require('url');
function App() {
var app = this;
this.server = http.createServer(function (request, response) {
app._onRequest(request, response);
});
this._callbacks = [];
this.port = 8000;
return this;
};
App.DONE = 1;
App.prototype.get = function (match, callback) {
this.request('GET', match, callback);
};
App.prototype.post = function (match, callback) {
this.request('POST', match, callback);
};
App.prototype.request = function (meth, match, callback) {
var regex = RegExp("^" + match.replace(/:[a-zA-Z\-\_0-9]+/, "([^/]*)") + "$");
this._callbacks.push(function (req) {
if (req.method != meth) { return; }
var matches = req.url.pathname.match(regex);
if (matches == null) { return; }
var response = callback.apply(this, matches.slice(1));
if (response.constructor == String) {
req._out(response);
}
else if (response == 404) {
this._handle404(req);
}
else if (response.constructor == Number) {
req.status = response;
req._out('');
}
throw App.DONE;
});
};
App.prototype._handle404 = function(req) {
req.status = 404;
var output = this._notFound(req);
req._out(output);
};
App.prototype._onRequest = function (request, response) {
var req = new Request(request, response);
try {
for (i in this._callbacks) { this._callbacks[i](req); }
}
catch (e) {
if (e != App.DONE) { throw e; }
return;
}
this._handle404(req);
};
// Default 404 handler
App.prototype._notFound = function (req) {
return "<h1>Not found</h1>Node doesn't know this ditty.";
};
App.prototype.run = function () {
sys.puts('Server running at http://127.0.0.1:'+this.port);
this.server.listen(this.port);
};
function Request (request, response) {
var _this = this;
this.request = request;
this.response = response;
this.url = url.parse(request.url); // pathname, search, href
this.method = request.method;
this.status = 200;
this.headers = {'Content-Type': 'text/html'};
this._out = function(str) {
response.writeHead(_this.status, _this.headers);
response.end(str);
sys.puts('[' + _this.status + '] ' + request.method + ' ' + request.url);
};
};
exports.App = App;
exports.Request = Request;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment