28 lines
1.1 KiB
JavaScript
28 lines
1.1 KiB
JavaScript
import http from 'node:http'
|
|
|
|
const prefix = '/extensions/qiu.subscription-admin'
|
|
const targetPort = Number(process.env.PLUGIN_TARGET_PORT || 18082)
|
|
const port = Number(process.env.MOCK_PROXY_PORT || 18081)
|
|
|
|
const server = http.createServer((req, res) => {
|
|
if (!req.url.startsWith(prefix)) {
|
|
res.writeHead(404)
|
|
res.end('not found')
|
|
return
|
|
}
|
|
const forwardedPath = req.url.slice(prefix.length) || '/'
|
|
const proxy = http.request({ hostname: '127.0.0.1', port: targetPort, method: req.method, path: forwardedPath, headers: { ...req.headers, host: `127.0.0.1:${targetPort}` } }, (upstream) => {
|
|
const headers = { ...upstream.headers }
|
|
if (headers.location && headers.location.startsWith('/admin/')) headers.location = `${prefix}${headers.location}`
|
|
res.writeHead(upstream.statusCode || 502, headers)
|
|
upstream.pipe(res)
|
|
})
|
|
proxy.on('error', () => {
|
|
if (!res.headersSent) res.writeHead(502)
|
|
res.end('proxy error')
|
|
})
|
|
req.pipe(proxy)
|
|
})
|
|
|
|
server.listen(port, '127.0.0.1', () => process.stdout.write(`mock proxy listening on 127.0.0.1:${port}\n`))
|