Skip to content

Instantly share code, notes, and snippets.

@ivarconr
Last active October 31, 2018 15:28
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 ivarconr/233fee769adae8ac5db44111fefc7ca2 to your computer and use it in GitHub Desktop.
Save ivarconr/233fee769adae8ac5db44111fefc7ca2 to your computer and use it in GitHub Desktop.
const async_hooks = require('async_hooks');
const fs = require('fs');
const http = require('http');
const fetch = require('node-fetch');
const asyncHook = async_hooks.createHook({
init: (asyncId, type, triggerAsyncId, resource) => {
if(type === 'TCPCONNECTWRAP') {
process.nextTick(() => {
console.log('TCPCONNECTWRAP');
// Unable to set header here (happens after TCPWRAP And socket:lookup)
});
}
if(type === 'TCPWRAP') {
process.nextTick(() => {
console.log(`${type} ${resource}`);
const socket = resource.owner;
socket.once('lookup', () => {
console.log('lookup');
//Not allowed
//socket.parser.outgoing.setHeader('User-Agent', 'boss');
//---
});
socket.once('data', () => {
// Pick up headers from incomming request!
if(socket.parser.incoming) {
console.log('Incomming user-agent: ' + socket.parser.incoming.headers['user-agent']);
}
});
});
}
}
});
asyncHook.enable();
http.createServer((req, res) => {
callAPI(() => {
res.end('hello\n');
})
}).listen(5000);
function callAPI(cb) {
fetch('http://localhost:3000', {
headers: { 'User-Agent': 'wrong - should be set' },
}).then(r => {
cb();
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment