package websocket import ( "context" "encoding/json" "fmt" "log" "mchess_server/api" "net/http" lobbies "mchess_server/lobby_registry" "github.com/gin-gonic/gin" gorillaws "github.com/gorilla/websocket" ) var upgrader = gorillaws.Upgrader{ CheckOrigin: func(r *http.Request) bool { return true }, } func RegisterWebSocketConnection(c *gin.Context) { log.Println(c.Request) conn, err := upgrader.Upgrade(c.Writer, c.Request, nil) if err != nil { log.Println(err) return } go waitForAndHandlePlayerID(c, conn) } func waitForAndHandlePlayerID(ctx context.Context, conn *gorillaws.Conn) { msgType, msg, err := conn.ReadMessage() if err != nil { errorMessage := fmt.Sprintf("Reading from websocket connection did not work: %s", err) log.Println(errorMessage) conn.Close() return } log.Println("read from websocket endpoint: ", msgType, string(msg), err) var info api.PlayerInfo err = json.Unmarshal(msg, &info) if err != nil { errorMessage := fmt.Sprintf("Unmarshaling message did not work: %s", err) log.Println(errorMessage) conn.WriteMessage(msgType, []byte(errorMessage)) conn.Close() return } lobby := lobbies.GetLobbyRegistry().GetLobbyByUUID(*info.LobbyID) if lobby == nil { conn.WriteMessage(msgType, []byte("lobby not found")) conn.Close() return } player, found := lobby.GetPlayerByUUID(*info.PlayerID) if !found { conn.WriteMessage(msgType, []byte("player not found")) conn.Close() return } if player.Conn.HasWebsocketConnection() { player.Conn.Close("closing existing connection") } lobby.Game.SetWebsocketConnectionFor(ctx, player, conn) log.Println("player after setting connection: ", player) } func ConnectWsForGame(c *gin.Context) { }