Last active
August 29, 2015 14:01
-
-
Save guileen/6c75068227a91351f552 to your computer and use it in GitHub Desktop.
http proxy for log
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var http = require('http'); | |
var httpProxy = require('http-proxy'); | |
var proxy = httpProxy.createProxyServer({}); | |
var cclog = require('cclog'); | |
var fs = require('fs'); | |
var zlib = require('zlib'); | |
var i = 1; | |
http.createServer(function(req, res) { | |
// req.setEncoding('utf-8'); | |
var basename = res.basename = __dirname + '/data/' + (i++) + '.' + req.headers.host; | |
var chunks = []; | |
req.on('data', function(data) { | |
chunks.push(data); | |
}); | |
req.on('end', function() { | |
cclog.log(req.method, req.url, req.headers); | |
fs.writeFile(basename + '.header', | |
'Method:' + req.method + | |
'\nURL:' + req.url + | |
'\nHeaders:' + JSON.stringify(req.headers, null, 2), cclog.ifError) | |
if(chunks.length > 0) { | |
var allbuffer = Buffer.concat(chunks); | |
fs.writeFile(basename + '.body', allbuffer, cclog.ifError); | |
} | |
}); | |
proxy.web(req, res, {target: req.url}); | |
}).listen(8080); | |
proxy.on('proxyRes', function(res) { | |
var basename = res.basename; | |
console.log('res.headers', res.headers); | |
fs.writeFile(basename + '.res.header', JSON.stringify(res.headers, null, 2), cclog.ifError) | |
var chunks = []; | |
res.on('data', function(data) { | |
chunks.push(data); | |
}); | |
res.on('end', function() { | |
var buffer = Buffer.concat(chunks); | |
if(res.headers['content-encoding'] == 'gzip') { | |
zlib.gunzip(buffer, function(err, buffer) { | |
log(buffer); | |
}) | |
} else { | |
log(buffer); | |
} | |
function log(buffer) { | |
var contentType = res.headers['content-type']; | |
if(contentType && contentType.indexOf('image') < 0) | |
cclog.info(buffer.toString('utf-8')); | |
fs.writeFile(basename + '.res.body', buffer, cclog.ifError); | |
}; | |
}) | |
}); | |
console.log('http proxy listen at 8080'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment