87 lines
1.9 KiB
Go
87 lines
1.9 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"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.GET("/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)
|
|
|
|
log.Println("responding with player id ", player.Uuid)
|
|
|
|
c.IndentedJSON(http.StatusOK, server.PlayerInfo{
|
|
PlayerID: player.Uuid,
|
|
})
|
|
}
|
|
|
|
func registerWebSocketConnection(c *gin.Context) {
|
|
// w http.ResponseWriter, r *http.Request
|
|
webSocketConn, err := websocket.Accept(c.Writer, c.Request, nil)
|
|
if err != nil {
|
|
log.Println(err)
|
|
return
|
|
}
|
|
go waitForAndHandlePlayerID(c, *webSocketConn)
|
|
}
|
|
|
|
func waitForAndHandlePlayerID(ctx context.Context, conn websocket.Conn) {
|
|
// var playerInfo server.PlayerInfo
|
|
|
|
msgType, id, err := conn.Read(ctx)
|
|
|
|
log.Println("read from websocket: ", msgType, id, err)
|
|
log.Println("id as string", string(id))
|
|
|
|
uuid, err := uuid.ParseBytes(id)
|
|
if err != nil {
|
|
log.Println(err)
|
|
conn.Close(websocket.StatusCode(400), err.Error())
|
|
return
|
|
}
|
|
|
|
lobby := server.GetLobby()
|
|
player, found := lobby[uuid]
|
|
if !found {
|
|
conn.Close(websocket.StatusCode(400), "player not found")
|
|
return
|
|
}
|
|
if player.Conn != nil {
|
|
player.Conn.Close(websocket.StatusCode(400), "closing existing connection")
|
|
}
|
|
player.Conn = &conn
|
|
}
|