Skip to content

Instantly share code, notes, and snippets.

@Unitech
Last active March 16, 2016 07:41
Show Gist options
  • Save Unitech/d0b957ed4152cb456360 to your computer and use it in GitHub Desktop.
Save Unitech/d0b957ed4152cb456360 to your computer and use it in GitHub Desktop.
Print user agent & co
var Proxy = require('./proxy.js');
var HttpWrap = module.exports = function(http) {
Proxy.wrap(http.Server.prototype, ['on', 'addListener'], function(addListener) {
return function(event, listener) {
if (!(event === 'request' && typeof listener === 'function')) return addListener.apply(this, arguments);
return addListener.call(this, event, function(request, response) {
var self = this;
var args = arguments;
var http_start = {
url : request.url,
method : request.method,
start : Date.now()
};
response.once('finish', function() {
console.log({
url : http_start.url,
method : http_start.method,
time : Date.now() - http_start.start,
code : response.statusCode,
size : response.getHeader('Content-Length'),
created_at : Date.now(),
header : request.header
})
});
});
return listener.apply(self, args);
});
};
});
return http;
};
var debug = require('debug')('proxy');
var Proxy = module.exports = {
wrap : function(object, methods, hook) {
var self = this;
if (!Array.isArray(methods)) methods = [methods];
methods.forEach(function(method) {
var original = object[method];
if (!original) return debug('Method %s unknown', method);
if (original.__axm_original) return debug('Already wrapped', object);
var hooked = hook(original);
hooked.__axm_original = original;
object[method] = hooked;
debug('Method proxified');
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment