HandleWebSocket handles WebSocket upgrade and communication
(c *gin.Context)
| 81 | |
| 82 | // HandleWebSocket handles WebSocket upgrade and communication |
| 83 | func (h *WebSocketHandler) HandleWebSocket(c *gin.Context) { |
| 84 | // Upgrade HTTP connection to WebSocket |
| 85 | conn, err := upgrader.Upgrade(c.Writer, c.Request, nil) |
| 86 | if err != nil { |
| 87 | logging.Error(c.Request.Context(), "websocket.upgrade.failed", map[string]any{ |
| 88 | "error": err.Error(), |
| 89 | }) |
| 90 | return |
| 91 | } |
| 92 | |
| 93 | // Create connection context |
| 94 | ctx, cancel := context.WithCancel(context.Background()) |
| 95 | |
| 96 | // Create connection object |
| 97 | wsConn := &WebSocketConnection{ |
| 98 | ID: fmt.Sprintf("ws-%d", time.Now().UnixNano()), |
| 99 | Conn: conn, |
| 100 | Send: make(chan []byte, 256), |
| 101 | ctx: ctx, |
| 102 | cancel: cancel, |
| 103 | } |
| 104 | |
| 105 | // Register connection |
| 106 | h.mu.Lock() |
| 107 | h.connections[wsConn.ID] = wsConn |
| 108 | h.mu.Unlock() |
| 109 | |
| 110 | logging.Info(ctx, "websocket.connected", map[string]any{ |
| 111 | "connection_id": wsConn.ID, |
| 112 | }) |
| 113 | |
| 114 | // Start write pump in goroutine |
| 115 | go h.writePump(wsConn) |
| 116 | |
| 117 | // Run read pump in current goroutine (blocks until connection closes) |
| 118 | h.readPump(wsConn) |
| 119 | } |
| 120 | |
| 121 | // readPump reads messages from the WebSocket connection |
| 122 | func (h *WebSocketHandler) readPump(wsConn *WebSocketConnection) { |