mchess-server/main.go

70 lines
1.4 KiB
Go
Raw Normal View History

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