From faad108b4d20bdd7f5326b988d7c371ec7b78156 Mon Sep 17 00:00:00 2001 From: Tom Anderson Date: Mon, 6 May 2024 14:25:12 -0700 Subject: [PATCH] Exposing a WebSocket Handler for embeded NATS servers There are more edge cases that this doesn't support, ideally the tradeoffs are valid if you understand them and need them --- server/websocket.go | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/server/websocket.go b/server/websocket.go index 8164917a7c7..071c92f3643 100644 --- a/server/websocket.go +++ b/server/websocket.go @@ -1099,6 +1099,29 @@ func (s *Server) wsConfigAuth(opts *WebsocketOpts) { ws.authOverride = opts.Username != _EMPTY_ || opts.Token != _EMPTY_ || opts.NoAuthUser != _EMPTY_ } +// HandleWebSocket allows for an embedded server to expose a NATS websocket Handler +// preventing the need to reverse proxy the NATS connection back into a separate +// port on the same process. By using this handler, the embedded server is responsible +// for handling the tls configurations as well as the requested origins, as the internal +// code in used by this handler will allow all origins. +// This endpoint does come with some limitations, such as not supporting MQTT or Leaf Nodes, +// as well as if the HTTP handler is not on the root path (/), most NATS clients will not be +// able to connect to the endpoint. The intention of this handler is for in browser +// websocket connections. +func (s *Server) HandleWebSocket(w http.ResponseWriter, r *http.Request) { + res, err := s.wsUpgrade(w, r) + if err != nil { + s.Errorf(err.Error()) + return + } + switch res.kind { + case CLIENT: + s.createWSClient(res.conn, res.ws) + default: + // all other cases are not supported on the direct WebSocket endpoint + } +} + func (s *Server) startWebsocketServer() { if s.isShuttingDown() { return