Created
October 31, 2018 11:40
-
-
Save ivarconr/c6a881e03f1e0f7bc02e5800eeb71017 to your computer and use it in GitHub Desktop.
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
const http = require('http'); | |
const fetch = require('node-fetch'); | |
const async_hooks = require('async_hooks'); | |
const context = new Map(); | |
const middleware = (req, res) => { | |
const id = async_hooks.executionAsyncId(); | |
const headers = req.headers; | |
context.set(id, headers); | |
res.on('finish', () => context.delete(id)); | |
}; | |
const getHeadersFromContext = () => { | |
return context.get(async_hooks.executionAsyncId()); | |
}; | |
http.createServer((req, res) => { | |
middleware(req, res); | |
//route handler of some sort | |
handleReq(req, res); | |
}).listen(5000); | |
function handleReq(req, res) { | |
// Somewhere else in app | |
const headers = getHeadersFromContext(); | |
fetch('http://localhost:3000', { | |
headers: { 'User-Agent': headers['user-agent'] }, | |
}).then(r => { | |
res.end('hello\n'); | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment