mchess-server/main.go
Marco eb946b4267 Many changes!
1. Use maintained websocket framework
2. Introduce function that allows to register a websocket connection per
   player
2023-04-22 21:41:24 +02:00

70 lines
1.4 KiB
Go

package main
import (
"local/m/mchess_server/server"
"log"
"net/http"
"os"
"github.com/gin-gonic/autotls"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"nhooyr.io/websocket"
)
var cert_path = "/etc/letsencrypt/live/chess.sw-gross.de/"
var cert_file = cert_path + "fullchain.pem"
var key_file = cert_path + "privkey.pem"
func main() {
hostname, err := os.Hostname()
if err != nil {
log.Fatal(err)
}
router := gin.Default()
router.GET("/api/random", registerForRandomGame)
router.POST("/api/ws", registerWebSocketConnection)
if hostname == "mbook" {
log.Println("Starting service WITHOUT TLS")
log.Fatal(router.Run("localhost:8080"))
} else {
log.Fatal(autotls.Run(router, "chess.sw-gross.de"))
}
}
func registerForRandomGame(c *gin.Context) {
player := server.NewPlayer(uuid.New())
server.GetLobby().RegisterPlayer(player)
c.IndentedJSON(http.StatusOK, server.PlayerInfo{
PlayerID: player.Uuid,
})
}
func registerWebSocketConnection(c *gin.Context) {
// w http.ResponseWriter, r *http.Request
var playerInfo server.PlayerInfo
err := c.BindJSON(&playerInfo)
if err != nil {
log.Printf("BindJSON has an error: (%e)", err)
}
log.Println("playerID:", playerInfo.PlayerID)
player, found := server.GetLobby()[playerInfo.PlayerID]
if found {
webSocketConn, err := websocket.Accept(c.Writer, c.Request, nil)
if err != nil {
log.Println(err)
return
}
player.Conn = *webSocketConn
}
}