Skip to content

Instantly share code, notes, and snippets.

@polotek
Created May 22, 2010 19:19
Show Gist options
  • Save polotek/410289 to your computer and use it in GitHub Desktop.
Save polotek/410289 to your computer and use it in GitHub Desktop.
// res.write is defined by the app framework to take callbacks; it stores the
// callbacks in a queue that ensures FIFO order, and when req.end is called it
// waits for all the write callbacks to finish before ending
var hello = function(req, res) {
res.writeHead(200, {});
res.write(function(){ this('Hello World'); };
res.end();
}
var contentType = function(app, type) {
return function contentTyper (req, res) {
var writeHead = res.writeHead;
res.writeHead = function(status, headers) {
headers['Content-Type'] = headers['Content-Type'] || type;
writeHead();
}
app(req, res);
}
}
var bounceFavIco = function(app) {
return function favIconBouncer(req, res) {
if (req.url == '/favicon.ico') {
res.writeHead(404, {});
res.end();
} else { app(req, res); }
}
}
var logger = function(app, config) {
config = config || {};
config.write = config.write || function(line) { require('sys').puts(line); };
config.formatter = config.formatter || function(vars) {
nowString: vars.date.toLocaleString();
return vars.remoteHost + " - " + vars.remoteUser + " [" + nowString + "] \"" + vars.method + " " + vars.path + " " + vars.httpVersion + "\" " + vars.status + " " + vars.contentLength + " " + vars.timer;
}
return function logg (req, res) {
var vars = {
sizing: false,
startTime: Number(new Date()),
remoteHost: req.headers['host'] || '-',
remoteUser: '-' // blah,
date: new Date(),
method: req.method,
path: req.url,
httpVersion: req.httpVersion
};
writeHead = res.writeHead;
write = res.write;
end = res.end;
}
res.writeHead = function(status, headers) {
vars.status = status;
vars.contentLength = headers['Content-Length'] || 0;
if (vars.contentLength == 0) { vars.sizing = true; }
writeHead(status, headers);
};
res.write = function(callback) {
var chunk = callback();
if (vars.sizing) { vars.contentLength += chunk.length; }
this(function() { this(chunk); });
}
res.end = function() {
vars.timer = Number(new Date()) - vars.startTime;
end();
config.write(config.formatter(vars));
}
app(req, res);
}
}
var app = neutrino(function() {
this.use logger;
this.use contentType, 'text/plain';
this.use bounceFavIco;
this.map '/admin', neutrino(function(){
this.use authentication;
this.run backend;
});
this.run hello;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment