36 lines
1.0 KiB
JavaScript
36 lines
1.0 KiB
JavaScript
const http = require('http');
|
|
const { URL } = require('url');
|
|
|
|
const listenPort = Number(process.env.PROXY_LISTEN_PORT || 81);
|
|
const target = new URL(process.env.PROXY_TARGET || 'http://127.0.0.1:18081');
|
|
|
|
const server = http.createServer((clientReq, clientRes) => {
|
|
const options = {
|
|
protocol: target.protocol,
|
|
hostname: target.hostname,
|
|
port: target.port,
|
|
method: clientReq.method,
|
|
path: clientReq.url,
|
|
headers: {
|
|
...clientReq.headers,
|
|
host: target.host
|
|
}
|
|
};
|
|
|
|
const proxyReq = http.request(options, proxyRes => {
|
|
clientRes.writeHead(proxyRes.statusCode || 502, proxyRes.headers);
|
|
proxyRes.pipe(clientRes);
|
|
});
|
|
|
|
proxyReq.on('error', error => {
|
|
clientRes.writeHead(502, { 'content-type': 'application/json; charset=utf-8' });
|
|
clientRes.end(JSON.stringify({ code: 502, message: error.message }));
|
|
});
|
|
|
|
clientReq.pipe(proxyReq);
|
|
});
|
|
|
|
server.listen(listenPort, '127.0.0.1', () => {
|
|
console.log(`proxy http://127.0.0.1:${listenPort} -> ${target.origin}`);
|
|
});
|