2015-11-06 01:00:22 +00:00
|
|
|
'use strict';
|
|
|
|
|
2015-11-06 11:05:32 +00:00
|
|
|
// Note the odd use of callbacks (instead of promises) here
|
|
|
|
// It's to avoid loading bluebird yet (see sni-server.js for explanation)
|
|
|
|
module.exports.create = function (certPaths, port, serverCallback) {
|
|
|
|
function initServer(err, server) {
|
|
|
|
var app;
|
|
|
|
var promiseApp;
|
2015-11-06 01:00:22 +00:00
|
|
|
|
2015-11-06 11:05:32 +00:00
|
|
|
if (err) {
|
|
|
|
serverCallback(err);
|
|
|
|
return;
|
|
|
|
}
|
2015-11-06 01:00:22 +00:00
|
|
|
|
2015-11-06 11:05:32 +00:00
|
|
|
server.on('error', serverCallback);
|
2015-11-14 04:25:12 +00:00
|
|
|
server.listen(port, '0.0.0.0', function () {
|
2015-11-06 11:05:32 +00:00
|
|
|
// is it even theoritically possible for
|
|
|
|
// a request to come in before this callback has fired?
|
|
|
|
// I'm assuming this event must fire before any request event
|
|
|
|
promiseApp = serverCallback(null, server);
|
2015-11-06 01:00:22 +00:00
|
|
|
});
|
2015-11-14 04:25:12 +00:00
|
|
|
/*
|
|
|
|
server.listen(port, '::::', function () {
|
|
|
|
// is it even theoritically possible for
|
|
|
|
// a request to come in before this callback has fired?
|
|
|
|
// I'm assuming this event must fire before any request event
|
|
|
|
promiseApp = serverCallback(null, server);
|
|
|
|
});
|
|
|
|
*/
|
2015-11-06 01:00:22 +00:00
|
|
|
|
|
|
|
// Get up and listening as absolutely quickly as possible
|
|
|
|
server.on('request', function (req, res) {
|
2015-11-06 11:05:32 +00:00
|
|
|
// this is a hot piece of code, so we cache the result
|
|
|
|
if (app) {
|
|
|
|
app(req, res);
|
|
|
|
return;
|
2015-11-06 01:00:22 +00:00
|
|
|
}
|
|
|
|
|
2015-11-06 11:05:32 +00:00
|
|
|
promiseApp.then(function (_app) {
|
2015-11-14 04:25:12 +00:00
|
|
|
console.log('[Server]', req.method, req.host || req.headers['x-forwarded-host'] || req.headers.host, req.url);
|
2015-11-06 11:05:32 +00:00
|
|
|
app = _app;
|
2015-11-06 01:00:22 +00:00
|
|
|
app(req, res);
|
|
|
|
});
|
|
|
|
});
|
2015-11-06 11:05:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
if (certPaths) {
|
|
|
|
require('./sni-server').create(certPaths, port, initServer);
|
|
|
|
} else {
|
|
|
|
initServer(null, require('http').createServer());
|
|
|
|
}
|
2015-11-06 01:00:22 +00:00
|
|
|
};
|