Skip to content

Instantly share code, notes, and snippets.

@kanreisa
Created May 21, 2014 06:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kanreisa/643a1d48d87e46afb882 to your computer and use it in GitHub Desktop.
Save kanreisa/643a1d48d87e46afb882 to your computer and use it in GitHub Desktop.
maniaxcache/2
/*jslint node:true, nomen:true, plusplus:true, regexp:true, vars:true, continue:true */
'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({
port : config.dest,
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/2',
'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(config.port, config.host);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment