75 lines
2.0 KiB
TypeScript
75 lines
2.0 KiB
TypeScript
import { handleRequest } from './module/index.ts';
|
|
import { config } from './module/config.ts';
|
|
import { app } from './app.ts';
|
|
import './route/route.ts';
|
|
import net from 'net';
|
|
import { WssApp } from './module/ws-proxy/index.ts';
|
|
|
|
const port = config?.proxy?.port || 3005;
|
|
|
|
app
|
|
.route({
|
|
path: 'hello',
|
|
key: '0',
|
|
})
|
|
.define(async (ctx) => {
|
|
ctx.body = 'hello world';
|
|
})
|
|
.addTo(app);
|
|
|
|
app.listen(port, () => {
|
|
console.log(`Server running at http://localhost:${port}/`);
|
|
});
|
|
|
|
app.server.on(handleRequest);
|
|
|
|
const wssApp = new WssApp();
|
|
const main = () => {
|
|
console.log('Upgrade initialization started');
|
|
|
|
app.server.server.on('upgrade', async (req, socket, head) => {
|
|
const isUpgrade = wssApp.upgrade(req, socket, head);
|
|
if (isUpgrade) {
|
|
console.log('WebSocket upgrade successful for path:', req.url);
|
|
return;
|
|
}
|
|
const proxyApiList = config?.apiList || [];
|
|
const proxyApi = proxyApiList.find((item) => req.url.startsWith(item.path));
|
|
|
|
if (proxyApi) {
|
|
const _u = new URL(req.url, `${proxyApi.target}`);
|
|
const options = {
|
|
hostname: _u.hostname,
|
|
port: Number(_u.port) || 80,
|
|
path: _u.pathname,
|
|
headers: req.headers,
|
|
};
|
|
|
|
const proxySocket = net.connect(options.port, options.hostname, () => {
|
|
proxySocket.write(
|
|
`GET ${options.path} HTTP/1.1\r\n` +
|
|
`Host: ${options.hostname}\r\n` +
|
|
`Connection: Upgrade\r\n` +
|
|
`Upgrade: websocket\r\n` +
|
|
`Sec-WebSocket-Key: ${req.headers['sec-websocket-key']}\r\n` +
|
|
`Sec-WebSocket-Version: ${req.headers['sec-websocket-version']}\r\n` +
|
|
`\r\n`,
|
|
);
|
|
proxySocket.pipe(socket);
|
|
socket.pipe(proxySocket);
|
|
});
|
|
|
|
proxySocket.on('error', (err) => {
|
|
console.error(`WebSocket proxy error: ${err.message}`);
|
|
socket.end();
|
|
});
|
|
} else {
|
|
socket.end();
|
|
}
|
|
});
|
|
};
|
|
|
|
setTimeout(() => {
|
|
main();
|
|
}, 1200);
|