Skip to content
This repository has been archived by the owner on Aug 20, 2024. It is now read-only.

Handling WebSocket Upgrade Request #43

Open
cloudwindy opened this issue Jan 25, 2022 · 0 comments
Open

Handling WebSocket Upgrade Request #43

cloudwindy opened this issue Jan 25, 2022 · 0 comments

Comments

@cloudwindy
Copy link

Hello, I'm using koa-better-http-proxy, and the following code to support websocket upgrade:

/**
 * Create a WebSocket server.
 * @param server Server
 */
createWebSocketServer(server: http.Server | https.Server | http2.Http2SecureServer) {
	server.on('upgrade', (req: http.IncomingMessage, sock: net.Socket, head: Buffer) => {
		server.emit('request', req, new UpgradableResponse(sock, head));
	});
	const createContext = this.app.createContext;
	this.app.createContext = (req: http.IncomingMessage, res: http.ServerResponse | UpgradableResponse) => {
		const ctx: Koa.Context = createContext.call(this.app, req, res);
		if (res instanceof UpgradableResponse) {
			ctx.ws = true;
			ctx.upgrade = () => res.upgrade(req);
		}
		return ctx;
	};
}

The UpgradeableReponse provides a upgrade method which returns a ws.WebSocket instance. Then the method is copied in the overridden createContext to be made accessible in ctx. ctx.ws is also set to true to indicate this connection is upgradable.

However, I can't figure out how to implement this in koa-better-http-proxy and act like nginx's proxy_pass.

@cloudwindy cloudwindy changed the title How to Handle WebSocket Upgrade Request? Handling WebSocket Upgrade Request Jan 25, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant