diff --git a/lib/sorting-hat.js b/lib/sorting-hat.js index 576eda2..1f2c91d 100644 --- a/lib/sorting-hat.js +++ b/lib/sorting-hat.js @@ -1,6 +1,8 @@ 'use strict'; + var os = require('os'); var path = require('path'); +var fs = require('fs'); module.exports.print = function (config) { var services = { https: {}, http: {}, tcp: {} }; @@ -95,6 +97,7 @@ module.exports.assign = function (state, tun, cb) { state._serveStatic = require('serve-static'); state._defaultServe = state._serveStatic(path.join(__dirname, 'html')); state.defaultHttpServer = require('http').createServer(function (req, res) { + // TODO serve api state._defaultServe(req, res, state._finalHandler(req, res)); }); } @@ -224,8 +227,9 @@ module.exports.assign = function (state, tun, cb) { } catch(e2) { console.error("Failed to require('" + handlerpath + "'):", e1.message); console.error("Failed to require('" + path.join(localshare, handlerpath) + "'):", e2.message); - console.warn("Using default handler for '" + handle + ":" + id + "'"); + console.warn("Trying static and index handlers for '" + handle + ":" + id + "'"); echoTcp(cb); + return; } } var socketPair = require('socket-pair'); @@ -298,7 +302,40 @@ module.exports.assign = function (state, tun, cb) { return; } - handlers.https(tlsSocket, tun, id); + fs.access(conf.handler, fs.constants.R_OK, function (err1) { + fs.stat(conf.handler, function (err2, stat) { + if (err1 || err2) { + // TODO handle errors + handlers.https(tlsSocket, tun, id); + return; + } + var isFile = stat.isFile(); + state._finalHandler = require('finalhandler'); + state._serveStatic = require('serve-static'); + state._serveIndex = require('serve-index'); + var serveIndex; + var serveStatic; + if (isFile) { + serveStatic = state._serveStatic(path.dirname(conf.handler), { dotfiles: 'allow', index: [ 'index.html' ] }); + serveIndex = function (req, res, next) { next(); }; + isFile = path.basename(conf.handler); + } else { + serveStatic = state._serveStatic(conf.handler, { dotfiles: 'allow', index: [ 'index.html' ] }); + serveIndex = state._serveIndex(conf.handler, { hidden: true, icons: true, view: 'tiles' }); + } + handler = function (req, res) { + if (isFile) { + req.url = '/' + isFile; + } + serveStatic(req, res, function () { + serveIndex(req, res, state._finalHandler(req, res)); + }); + }; + handlerservers[conf.handler] = http.createServer(handler); + handlerservers[conf.handler].emit('connection', tlsSocket); + process.nextTick(function () { tlsSocket.resume(); }); + }); + }); } function terminateTls(tun, cb) {