haste-server/server.js

63 lines
1.7 KiB
JavaScript
Raw Normal View History

2011-11-18 16:17:41 +01:00
var http = require('http');
var url = require('url');
var fs = require('fs');
2011-11-18 16:17:41 +01:00
2011-11-18 21:44:28 +01:00
var winston = require('winston');
2011-11-18 21:51:38 +01:00
var StaticHandler = require('./lib/static_handler');
var DocumentHandler = require('./lib/document_handler');
2011-11-18 23:54:57 +01:00
var FileDocumentStore = require('./lib/file_document_store');
2011-11-18 21:44:28 +01:00
2011-11-18 22:57:23 +01:00
// Load the configuration and set some defaults
var config = JSON.parse(fs.readFileSync('config.js', 'utf8'));
2011-11-18 22:57:23 +01:00
config.port = config.port || 7777;
config.host = config.host || 'localhost';
2011-11-18 23:26:25 +01:00
// Set up the logger
if (config.logging) {
try {
winston.remove(winston.transports.Console);
} catch(er) { }
var detail, type;
for (var i = 0; i < config.logging.length; i++) {
detail = config.logging[i];
type = detail.type;
delete detail.type;
winston.add(winston.transports[type], detail);
}
}
2011-11-18 16:17:41 +01:00
2011-11-18 22:37:18 +01:00
// TODO implement command line
2011-11-18 16:17:41 +01:00
2011-11-18 21:51:38 +01:00
// Set the server up
2011-11-18 16:17:41 +01:00
http.createServer(function(request, response) {
2011-11-18 16:49:00 +01:00
var incoming = url.parse(request.url, false);
2011-11-18 16:49:38 +01:00
var handler = null;
2011-11-18 21:44:28 +01:00
// Looking to add a new doc
if (incoming.pathname.match(/^\/documents$/) && request.method == 'POST') {
2011-11-18 23:54:57 +01:00
handler = new DocumentHandler({
keyLength: config.keyLength,
store: new FileDocumentStore('./data')
});
2011-11-18 21:51:38 +01:00
return handler.handlePost(request, response);
2011-11-18 16:49:00 +01:00
}
2011-11-18 21:44:28 +01:00
// Looking up a doc
2011-11-18 21:51:38 +01:00
var match = incoming.pathname.match(/^\/documents\/([A-Za-z0-9]+)$/);
if (request.method == 'GET' && match) {
2011-11-18 23:54:57 +01:00
handler = new DocumentHandler({
store: new FileDocumentStore('./data')
});
2011-11-18 21:51:38 +01:00
return handler.handleGet(match[1], response);
2011-11-18 21:44:28 +01:00
}
// Otherwise, look for static file
2011-11-18 21:51:38 +01:00
handler = new StaticHandler('./static');
2011-11-18 22:00:05 +01:00
handler.handle(incoming.pathname, response);
2011-11-18 16:17:41 +01:00
2011-11-18 22:57:23 +01:00
}).listen(config.port, config.host);
2011-11-18 22:58:21 +01:00
winston.info('listening on ' + config.host + ':' + config.port);