|
| 1 | +import { createServer, get } from 'http'; |
| 2 | +import { get as httpsGet } from 'https'; |
| 3 | + |
| 4 | +const server = createServer(function (req, res) { |
| 5 | + const url = new URL(req.url, 'http://localhost:8080'); |
| 6 | + |
| 7 | + // Outbound HTTP proxy: the container makes an HTTP request to the given host. |
| 8 | + const proxyTarget = url.searchParams.get('proxy'); |
| 9 | + if (proxyTarget) { |
| 10 | + get('http://' + proxyTarget, proxyRes => { |
| 11 | + let body = ''; |
| 12 | + proxyRes.on('data', chunk => { |
| 13 | + body += chunk; |
| 14 | + }); |
| 15 | + proxyRes.on('end', () => { |
| 16 | + res.writeHead(proxyRes.statusCode, { 'Content-Type': 'text/plain' }); |
| 17 | + res.end(body); |
| 18 | + }); |
| 19 | + }).on('error', err => { |
| 20 | + res.writeHead(520, { 'Content-Type': 'text/plain' }); |
| 21 | + res.end('proxy error: ' + err.message); |
| 22 | + }); |
| 23 | + return; |
| 24 | + } |
| 25 | + |
| 26 | + // Outbound HTTPS proxy: uses NODE_EXTRA_CA_CERTS (set via env) to trust |
| 27 | + // the Cloudflare containers CA for intercepted HTTPS. |
| 28 | + const proxyHttpsTarget = url.searchParams.get('proxy_https'); |
| 29 | + if (proxyHttpsTarget) { |
| 30 | + httpsGet('https://' + proxyHttpsTarget, proxyRes => { |
| 31 | + let body = ''; |
| 32 | + proxyRes.on('data', chunk => { |
| 33 | + body += chunk; |
| 34 | + }); |
| 35 | + proxyRes.on('end', () => { |
| 36 | + res.writeHead(proxyRes.statusCode, { 'Content-Type': 'text/plain' }); |
| 37 | + res.end(body); |
| 38 | + }); |
| 39 | + }).on('error', err => { |
| 40 | + res.writeHead(520, { 'Content-Type': 'text/plain' }); |
| 41 | + res.end('proxy_https error: ' + err.message); |
| 42 | + }); |
| 43 | + return; |
| 44 | + } |
| 45 | + |
| 46 | + res.writeHead(200, { 'Content-Type': 'text/plain' }); |
| 47 | + res.end('Hello from egress test container'); |
| 48 | +}); |
| 49 | + |
| 50 | +server.listen(8080, function () { |
| 51 | + console.log('Egress test server listening on port 8080'); |
| 52 | +}); |
| 53 | + |
| 54 | +process.on('SIGTERM', () => { |
| 55 | + server.close(() => { |
| 56 | + process.exit(0); |
| 57 | + }); |
| 58 | +}); |
0 commit comments