update
This commit is contained in:
59
src/index.ts
59
src/index.ts
@@ -1,11 +1,62 @@
|
||||
import { config } from './modules/config.ts';
|
||||
import { myConfig as config } from './modules/config.ts';
|
||||
import { app } from './app.ts';
|
||||
import './route.ts';
|
||||
import { uploadMiddleware } from './routes-simple/upload.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(uploadMiddleware);
|
||||
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);
|
||||
Reference in New Issue
Block a user