Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

wip #1

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 97 additions & 0 deletions lib/compress.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
var send = require('send');
var debug = require('debug')('compress');
var parse = require('url').parse;
var fs = require('fs');
var path = require('path');
var mime = send.mime;

function setHeader(res, path, encoding) {
var type = mime.lookup(path);
var charset = mime.charsets.lookup(type);

debug('content-type %s', type);
res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : ''));
res.setHeader('Content-Encoding', encoding);
res.setHeader('Vary', 'Accept-Encoding');
}

function handleGzipBroti(root, options) {
var setHeaders = options.setHeaders;

var methods = [];
if (options.brotli) {
methods.push({ extension: '.br', encoding: 'br' });
}
if (options.gzip) {
methods.push({ extension: '.gz', encoding: 'gzip' });
}

function checkExtension(req, method) {
var acceptEncoding = req.headers['accept-encoding'] || '';
if (!~acceptEncoding.indexOf(method.encoding)) {
return;
}

var name = {
orig: parse(req.url).pathname
};

if (name.orig[name.orig.length - 1] === '/') {
name.compressed = name.orig;
name.orig += options.index;
name.index = options.index + method.extension;
}
else {
name.compressed = name.orig + method.extension;
}
name.full = path.join(root, name.orig + method.extension);
debug('request %s, check for %s', req.url, name.full);

try {
var stats = fs.statSync(name.full);
if (!stats.isDirectory()) {
name.encoding = method.encoding;
return name;
}
}
catch (e) {
// file probably didn't exist
}
}

return function (req, res, next) {
if (req.method !== 'GET' && req.method !== 'HEAD') {
return next();
}

var name;
for (var i = 0; !name && i < methods.length; i++) {
name = checkExtension(req, methods[i]);
}
if (!name) {
debug('Passing %s', req.url);
return next();
}

debug('Sending %s', name.full);
setHeader(res, name.orig, name.encoding);

var stream = send(req, name.compressed, {
maxAge: options.maxAge || 0,
root: root,
index: name.index,
cacheControl: options.cacheControl,
lastModified: options.lastModified,
etag: options.etag,
dotfiles: options.dotfiles
})
.on('error', next);

if (setHeaders) {
stream.on('headers', setHeaders);
}
stream.pipe(res);
};
}

module.exports = handleGzipBroti;
137 changes: 86 additions & 51 deletions lib/http-server.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
'use strict';

var fs = require('fs'),
union = require('union'),
ecstatic = require('ecstatic'),
express = require('express'),
serveStatic = require('serve-static'),
serveIndex = require('serve-index'),
auth = require('basic-auth'),
httpProxy = require('http-proxy'),
corser = require('corser'),
secureCompare = require('secure-compare');
cors = require('cors'),
secureCompare = require('secure-compare'),
compress = require('./compress');

//
// Remark: backwards compatibility for previous
Expand Down Expand Up @@ -66,17 +68,17 @@ function HttpServer(options) {
}

var before = options.before ? options.before.slice() : [];
var app = express();

before.push(function (req, res) {
app.use(function (req, res, next) {
if (options.logFn) {
options.logFn(req, res);
}

res.emit('next');
next();
});

if (options.username || options.password) {
before.push(function (req, res) {
app.use(function (req, res, next) {
var credentials = auth(req);

// We perform these outside the if to avoid short-circuiting and giving
Expand All @@ -86,7 +88,7 @@ function HttpServer(options) {
var usernameEqual = secureCompare(options.username, credentials.name);
var passwordEqual = secureCompare(options.password, credentials.pass);
if (usernameEqual && passwordEqual) {
return res.emit('next');
return next();
}
}

Expand All @@ -97,19 +99,11 @@ function HttpServer(options) {
}

if (options.cors) {
this.headers['Access-Control-Allow-Origin'] = '*';
this.headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Range';
if (options.corsHeaders) {
options.corsHeaders.split(/\s*,\s*/)
.forEach(function (h) { this.headers['Access-Control-Allow-Headers'] += ', ' + h; }, this);
}
before.push(corser.create(options.corsHeaders ? {
requestHeaders: this.headers['Access-Control-Allow-Headers'].split(/\s*,\s*/)
} : null));
app.use(cors());
}

if (options.robots) {
before.push(function (req, res) {
app.use(function (req, res, next) {
if (req.url === '/robots.txt') {
res.setHeader('Content-Type', 'text/plain');
var robots = options.robots === true
Expand All @@ -119,26 +113,46 @@ function HttpServer(options) {
return res.end(robots);
}

res.emit('next');
next();
});
}

before.push(ecstatic({
root: this.root,
cache: this.cache,
showDir: this.showDir,
showDotfiles: this.showDotfiles,
autoIndex: this.autoIndex,
defaultExt: this.ext,
gzip: this.gzip,
brotli: this.brotli,
contentType: this.contentType,
handleError: typeof options.proxy !== 'string'
}));
app.use(function (req, res, next) {
for (var key in this.headers) {
if (this.headers.hasOwnProperty(key)) {
res.setHeader(key, this.headers[key]);
}
}
next();
}.bind(this));

var staticOptions = {
// cache: this.cache,
dotfiles: this.showDotfiles ? 'allow' : 'ignore',
index: this.autoIndex ? ['index.html'] : false,
extensions: this.ext ? [this.ext] : false
// contentType: this.contentType,
// handleError: typeof options.proxy !== 'string'
};

if (this.gzip || this.brotli) {
app.use(compress(this.root, Object.assign({}, staticOptions, {
gzip: this.gzip,
brotli: this.brotli
})));
}

app.use(serveStatic(this.root, staticOptions));

if (this.showDir) {
app.use(serveIndex(this.root, {
icons: true
}));
}

if (typeof options.proxy === 'string') {
var proxy = httpProxy.createProxyServer({});
before.push(function (req, res) {
app.use(function (req, res, next) {
proxy.web(req, res, {
target: options.proxy,
changeOrigin: true
Expand All @@ -148,34 +162,55 @@ function HttpServer(options) {
message: err.message,
status: res.statusCode });
}
res.emit('next');
next();
});
});
}

var serverOptions = {
before: before,
headers: this.headers,
onError: function (err, req, res) {
if (options.logFn) {
options.logFn(req, res, err);
}

res.end();
app.use(function (req, res) {
if (options.logFn) {
options.logFn(req, res, {
message: 'not found',
status: 404 });
}
};

if (options.https) {
serverOptions.https = options.https;
}
res.status(404);
res.end('(404) Not Found: ' + req.url);
});

this.server = union.createServer(serverOptions);
this.app = app;
// listen(8080, hostname);
// var serverOptions = {
// before: before,
// headers: this.headers,
// onError: function (err, req, res) {
// if (options.logFn) {
// options.logFn(req, res, err);
// }
//
// res.end();
// }
// };
//
// if (options.https) {
// serverOptions.https = options.https;
// }
//
// this.server = union.createServer(serverOptions);
console.log('-----');
setTimeout(function () {
this.server.close();
}.bind(this), 5 * 1000);
}

var util = require('util');
util.print = function () {
throw new Error('foo:' + (new Error('')).stack);
};

HttpServer.prototype.listen = function () {
this.server.listen.apply(this.server, arguments);
this.server = this.app.listen.apply(this.app, arguments);
};

HttpServer.prototype.close = function () {
return this.server.close();
return this.server.destroy();
};
Loading