Minetrack/lib/server.js

61 lines
1.4 KiB
JavaScript
Raw Normal View History

var http = require('http');
var fs = require('fs');
var url = require('url');
var mime = require('mime');
var io = require('socket.io');
2015-11-02 05:46:24 +00:00
var logger = require('./logger');
var config = require('../config.json');
exports.start = function(callback) {
var urlMapping = [];
var routeKeys = Object.keys(config.routes);
// Map the (static) routes from our config.
for (var i = 0; i < routeKeys.length; i++) {
urlMapping[routeKeys[i]] = config.routes[routeKeys[i]];
}
2015-11-02 05:46:24 +00:00
logger.log('info', Object.keys(config.routes));
// Create our tiny little HTTP server.
var server = http.createServer(function(req, res) {
var requestUrl = url.parse(req.url).pathname;
2015-11-02 07:08:54 +00:00
logger.log('info', '%s requested: %s', req.connection.remoteAddress, requestUrl);
2015-11-09 07:03:03 +00:00
if (requestUrl === '/status.json') {
res.setHeader('Content-Type', 'text/plain');
2015-12-19 03:23:24 +00:00
2015-11-09 07:03:03 +00:00
res.write(JSON.stringify({
error: true,
message: 'API deprecated.'
}));
res.end();
} else if (requestUrl in urlMapping) {
var file = urlMapping[requestUrl];
res.setHeader('Content-Type', mime.lookup(file));
fs.createReadStream(file).pipe(res);
} else {
res.statusCode = 404;
2015-12-19 03:23:24 +00:00
res.write('404');
res.end();
}
});
server.listen(config.site.port, config.site.ip);
// I don't like this. But it works, I think.
2015-12-19 03:23:24 +00:00
exports.io = io.listen(server);
// Since everything is loaded, do some final prep work.
2015-11-02 05:46:24 +00:00
logger.log('info', 'Started on %s:%d', config.site.ip, config.site.port);
callback();
};