62 lines
1.9 KiB
TypeScript
62 lines
1.9 KiB
TypeScript
import { myConfig as config } from './modules/config.ts';
|
|
import { app } from './app.ts';
|
|
import './route.ts';
|
|
import { handleRequest } from './routes-simple/handle-request.ts';
|
|
import { port } from './modules/config.ts';
|
|
import { WssApp } from './modules/ws-proxy/index.ts';
|
|
import net from 'node:net';
|
|
// if (import.meta.url === `file://${process.argv[1]}`) {
|
|
app.listen(port, () => {
|
|
console.log(`server is 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); |