Skip to content

Instantly share code, notes, and snippets.

@kanreisa kanreisa/index.js
Created Sep 20, 2014

Embed
What would you like to do?
maniaxcache/3
'use strict';
var config = require('./config.json');
var dncs = config.dncs || [];
var dncsLength = dncs.length;
var util = require('util');
var http = require('http');
var cacheTable = {};
var httpServer = http.createServer(function (req, res) {
var reqTime = Date.now();
var i, dnc = false;
if (req.method === 'GET' || req.method === 'HEAD') {
for (i = 0; i < dncsLength; i++) {
if (new RegExp(dncs[i]).test(req.url)) {
dnc = true;
break;
}
}
} else {
dnc = true;
}
if (dnc === true || !cacheTable[req.url]) {
if (dnc === false) {
delete req.headers.cookie;
delete req.headers.dnt;
delete req.headers.pragma;
delete req.headers.referer;
delete req.headers['cache-control'];
}
var proxy = http.request({
host : config.host,
port : config.port,
//headers: req.headers,
method : req.method,
path : req.url
});
req.pipe(proxy);
proxy.on('response', function (r) {
if (dnc === true || r.statusCode !== 200 || req.method !== 'GET') {
res.writeHead(r.statusCode, r.headers);
} else {
r.headers['x-maniaxcache-status'] = 'miss';
var cache = {
h: {
'Content-Type': r.headers['content-type'],
Server: 'maniaxcache/3',
'X-Maniaxcache-Status': dnc ? 'ignored' : 'miss'
}
};
var buffers = [];
r.on('data', function (chunk) {
buffers.push(chunk);
});
r.on('end', function () {
cache.b = Buffer.concat(buffers);
delete cache.h.date;
cache.h['X-Maniaxcache-Status'] = 'hit';
cacheTable[req.url] = cache;
});
res.writeHead(r.statusCode, cache.h);
}
r.pipe(res);
var durTime = Date.now() - reqTime;
// print log
process.nextTick(function () {
util.log([
r.statusCode,
req.method + ':' + req.url,
req.client.remoteAddress,
(req.headers['user-agent'] || '').split(' ').pop() || '-',
durTime
].join(' '));
});
});
proxy.on('error', function (e) {
util.log(e);
});
} else {
res.writeHead(200, cacheTable[req.url].h);
if (req.method === 'HEAD') {
res.end();
} else {
res.end(cacheTable[req.url].b);
}
var durTime = Date.now() - reqTime;
// print log
process.nextTick(function () {
util.log([
200,
req.method + ':' + req.url,
req.client.remoteAddress,
(req.headers['user-agent'] || '').split(' ').pop() || '-',
durTime
].join(' '));
});
}
});
httpServer.listen(process.env.PORT || 8080, '0.0.0.0');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.