mchess-server/api/handler/websocket.go

84 lines
1.8 KiB
Go
Raw Normal View History

2024-05-12 13:42:40 +00:00
package handler
import (
"context"
"encoding/json"
"fmt"
"log"
"mchess_server/api"
"mchess_server/utils"
"net/http"
"mchess_server/lobbies"
"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) {
2024-05-12 13:42:40 +00:00
limiter.Take()
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) {
2024-05-12 13:42:40 +00:00
limiter.Take()
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().GetLobbyByPassphrase(utils.NewPassphraseFromString(*info.Passphrase))
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
}
lobby.Game.SetWebsocketConnectionFor(ctx, player, conn)
log.Println("player after setting connection: ")
log.Println("id: ", player.Uuid)
log.Println("color: ", player.GetColor())
log.Println("Connection: ", player.Conn.ID)
}
func ConnectWsForGame(c *gin.Context) {
2024-05-12 13:42:40 +00:00
limiter.Take()
}