(options = {})
| 17 | // This creates a minimal proxy server that logs the requests it gets |
| 18 | // to an array before performing proxying. |
| 19 | function createProxyServer(options = {}) { |
| 20 | const logs = []; |
| 21 | |
| 22 | let proxy; |
| 23 | if (options.https) { |
| 24 | const common = require('../common'); |
| 25 | if (!common.hasCrypto) { |
| 26 | common.skip('missing crypto'); |
| 27 | } |
| 28 | proxy = require('https').createServer({ |
| 29 | cert: require('./fixtures').readKey('agent9-cert.pem'), |
| 30 | key: require('./fixtures').readKey('agent9-key.pem'), |
| 31 | }); |
| 32 | } else { |
| 33 | proxy = http.createServer(); |
| 34 | } |
| 35 | proxy.on('request', (req, res) => { |
| 36 | logRequest(logs, req); |
| 37 | const { hostname, port } = new URL(`http://${req.headers.host}`); |
| 38 | const targetPort = port || 80; |
| 39 | |
| 40 | const url = new URL(req.url); |
| 41 | const options = { |
| 42 | hostname: hostname.startsWith('[') ? hostname.slice(1, -1) : hostname, |
| 43 | port: targetPort, |
| 44 | path: url.pathname + url.search, // Convert back to relative URL. |
| 45 | method: req.method, |
| 46 | headers: { |
| 47 | ...req.headers, |
| 48 | 'connection': req.headers['proxy-connection'] || 'close', |
| 49 | }, |
| 50 | }; |
| 51 | |
| 52 | const proxyReq = http.request(options, (proxyRes) => { |
| 53 | res.writeHead(proxyRes.statusCode, proxyRes.headers); |
| 54 | proxyRes.pipe(res, { end: true }); |
| 55 | }); |
| 56 | |
| 57 | proxyReq.on('error', (err) => { |
| 58 | logs.push({ error: err, source: 'proxy request' }); |
| 59 | if (!res.headersSent) { |
| 60 | res.writeHead(500); |
| 61 | } |
| 62 | if (!res.writableEnded) { |
| 63 | res.end(`Proxy error ${err.code}: ${err.message}`); |
| 64 | } |
| 65 | }); |
| 66 | |
| 67 | res.on('error', (err) => { |
| 68 | logs.push({ error: err, source: 'client response for request' }); |
| 69 | }); |
| 70 | |
| 71 | req.pipe(proxyReq, { end: true }); |
| 72 | }); |
| 73 | |
| 74 | proxy.on('connect', (req, res, head) => { |
| 75 | logRequest(logs, req); |
| 76 |
no test coverage detected
searching dependent graphs…