|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const common = require('../common'); |
| 4 | +const fixtures = require('../common/fixtures'); |
| 5 | +const assert = require('assert'); |
| 6 | +const { spawn } = require('child_process'); |
| 7 | +const http = require('http'); |
| 8 | +const { onConnect } = require('../fixtures/proxy-handler'); |
| 9 | + |
| 10 | +// Start a server to process the final request. |
| 11 | +const server = http.createServer((req, res) => { |
| 12 | + res.end('Hello world'); |
| 13 | +}); |
| 14 | +server.on('error', (err) => { console.log('Server error', err); }); |
| 15 | + |
| 16 | +server.listen(0, common.mustCall(() => { |
| 17 | + // Start a proxy server to tunnel the request. |
| 18 | + const proxy = http.createServer(); |
| 19 | + // If the request does not go through the proxy server, common.mustCall fails. |
| 20 | + proxy.on('connect', common.mustCall((req, clientSocket, head) => { |
| 21 | + console.log('Proxying CONNECT', req.url, req.headers); |
| 22 | + assert.strictEqual(req.url, `localhost:${server.address().port}`); |
| 23 | + onConnect(req, clientSocket, head); |
| 24 | + })); |
| 25 | + proxy.on('error', (err) => { console.log('Proxy error', err); }); |
| 26 | + |
| 27 | + proxy.listen(0, common.mustCall(() => { |
| 28 | + const proxyAddress = `http://localhost:${proxy.address().port}`; |
| 29 | + const serverAddress = `http://localhost:${server.address().port}`; |
| 30 | + const child = spawn(process.execPath, |
| 31 | + [fixtures.path('fetch-and-log.mjs')], |
| 32 | + { |
| 33 | + env: { |
| 34 | + ...process.env, |
| 35 | + HTTP_PROXY: proxyAddress, |
| 36 | + NODE_USE_ENV_PROXY: true, |
| 37 | + SERVER_ADDRESS: serverAddress, |
| 38 | + }, |
| 39 | + }); |
| 40 | + |
| 41 | + const stderr = []; |
| 42 | + const stdout = []; |
| 43 | + child.stderr.on('data', (chunk) => { |
| 44 | + stderr.push(chunk); |
| 45 | + }); |
| 46 | + child.stdout.on('data', (chunk) => { |
| 47 | + stdout.push(chunk); |
| 48 | + }); |
| 49 | + |
| 50 | + child.on('exit', common.mustCall(function(code, signal) { |
| 51 | + proxy.close(); |
| 52 | + server.close(); |
| 53 | + |
| 54 | + console.log('--- stderr ---'); |
| 55 | + console.log(Buffer.concat(stderr).toString()); |
| 56 | + console.log('--- stdout ---'); |
| 57 | + const stdoutStr = Buffer.concat(stdout).toString(); |
| 58 | + console.log(stdoutStr); |
| 59 | + assert.strictEqual(stdoutStr.trim(), 'Hello world'); |
| 60 | + assert.strictEqual(code, 0); |
| 61 | + assert.strictEqual(signal, null); |
| 62 | + })); |
| 63 | + })); |
| 64 | +})); |
0 commit comments