From 9fa47243c5de11233ccd6967127714456c7c093d Mon Sep 17 00:00:00 2001 From: Jacobtread Date: Mon, 7 Mar 2022 18:23:21 +1300 Subject: [PATCH] Removed Gin and used my packet system library --- backend/app.go | 97 +++++++++++------------------------ backend/game/game.go | 11 ++-- backend/game/player.go | 5 +- backend/go.mod | 24 ++------- backend/go.sum | 114 ++--------------------------------------- backend/net/client.go | 14 ++--- backend/net/net.go | 84 ------------------------------ backend/net/server.go | 21 ++++---- 8 files changed, 65 insertions(+), 305 deletions(-) delete mode 100644 backend/net/net.go diff --git a/backend/app.go b/backend/app.go index 69e0216..ae85a08 100644 --- a/backend/app.go +++ b/backend/app.go @@ -6,14 +6,13 @@ import ( "backend/tools" _ "embed" "fmt" - "github.com/gin-gonic/gin" - "github.com/gorilla/websocket" + "github.com/jacobtread/gowsps" "log" "net/http" ) const ( - Version = "1.0.4" + Version = "1.0.5" Intro = ` __ __ ___ __ / \ | | | / | |__ |__) @@ -35,87 +34,53 @@ var appIndex []byte func main() { address := tools.EnvOrDefault("QUIZLER_ADDRESS", "0.0.0.0") // Retrieve the address environment variable port := tools.EnvOrDefault("QUIZLER_PORT", "8080") // Retrieve the port environment variable - - // Create a host url from ADDRESS:PORT - host := fmt.Sprintf("%s:%s", address, port) + host := fmt.Sprintf("%s:%s", address, port) // Create a host url from ADDRESS:PORT fmt.Printf(Intro, Version, port) // Print the intro message - gin.SetMode(gin.ReleaseMode) // Set Gin to "Release" mode (Not debug mode) - g := gin.New() // Create a new gin instance - - g.Use(gin.Recovery()) // Recovery middleware to recover from panics and send 500 instead - - g.GET("/ws", SocketConnect) // Create a new web socket endpoint - - // Serve the index page if the websocket was not requested - g.NoRoute(func(context *gin.Context) { - // Serve the index.html file - context.Data(http.StatusOK, "text/html", appIndex) + // Create a handler for handling http requests + http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) { + if request.URL.Path == "/ws" { // If the user accessed the websocket endpoint + SocketConnect(writer, request) // Create a socket connection + } else { + writer.Header().Set("Content-Type", "text/html") // Set the Content-Type as HTML + _, _ = writer.Write(appIndex) // Write the index HTML body to the response + } }) - // Run the server - err := g.Run(host) - if err != nil { - log.Fatal("An error occurred", err) + err := http.ListenAndServe(host, nil) // Listen on the provided address + if err != nil { // If we encountered an error + log.Fatal("An error occurred", err) // Print out the error } } -// upgrader Used to upgrade HTTP requests to the WS protocol -var upgrader = websocket.Upgrader{CheckOrigin: func(r *http.Request) bool { return true }} - // SocketState A structure representing the state of a socket instance type SocketState struct { Hosted *game.Game // The hosted player Game *game.Game // The active game Player *game.Player // The active player - *Connection // The websocket connection + *gowsps.Connection // The websocket connection } //SocketConnect Creates a socket connection and upgrades the HTTP request to WS -func SocketConnect(c *gin.Context) { - // Try to upgrade the http connection to a web socket connection - ws, err := upgrader.Upgrade(c.Writer, c.Request, nil) - if err != nil { // If we failed to upgrade the connection - log.Fatal("Failed to upgrade connection", err) - } - // Deferred closing of the socket when we are done this will result - // in ws.Close being called after this function is finished executing - defer func(ws *websocket.Conn) { _ = ws.Close() }(ws) - - var rawPacket = PacketRaw{} // The structure for packets to be decoded into as id and raw dat - conn := NewConnection(ws) // Create a new connection - var state = SocketState{Connection: conn} // Create a new state with the connection - - for conn.Open { // As long as the connection is still open - // Read incoming packet into the raw packet map - err = ws.ReadJSON(&rawPacket) - if err != nil { // If packet parsing failed or the ID was missing - if conn.Open { // Ignore this message if the client is not connected any more - // Disconnect the client for sending invalid data - conn.Send(DisconnectPacket("Failed to decode packet")) - } - break - } +func SocketConnect(w http.ResponseWriter, r *http.Request) { + s := gowsps.NewPacketSystem() + var state = SocketState{} // Create a new state with the connection + + // Add handlers for each of + gowsps.AddHandler(s, CCreateGame, state.onCreateGame) + gowsps.AddHandler(s, CCheckNameTaken, state.onCheckNameTaken) + gowsps.AddHandler(s, CRequestGameState, state.onRequestGameState) + gowsps.AddHandler(s, CRequestJoin, state.onRequestJoin) + gowsps.AddHandler(s, CStateChange, state.onStateChange) + gowsps.AddHandler(s, CAnswer, state.onAnswer) + gowsps.AddHandler(s, CKick, state.onKick) + + s.UpgradeAndListen(w, r, func(conn *gowsps.Connection, err error) { + state.Connection = conn + }) - switch rawPacket.Id { - case CCreateGame: - HandlePacket(rawPacket, state.onCreateGame) - case CCheckNameTaken: - HandlePacket(rawPacket, state.onCheckNameTaken) - case CRequestGameState: - HandlePacket(rawPacket, state.onRequestGameState) - case CRequestJoin: - HandlePacket(rawPacket, state.onRequestJoin) - case CStateChange: - HandlePacket(rawPacket, state.onStateChange) - case CAnswer: - HandlePacket(rawPacket, state.onAnswer) - case CKick: - HandlePacket(rawPacket, state.onKick) - } - } state.Cleanup() // Cleanup the state } diff --git a/backend/game/game.go b/backend/game/game.go index 268254b..163e777 100644 --- a/backend/game/game.go +++ b/backend/game/game.go @@ -3,6 +3,7 @@ package game import ( "backend/net" . "backend/tools" + . "github.com/jacobtread/gowsps" "log" "math" "strings" @@ -21,7 +22,7 @@ const ( // Game a structure representing the game itself type Game struct { - Host *net.Connection // The connection to the game host + Host *Connection // The connection to the game host Id Identifier // The unique identifier / game code for this game Title string // The title / name of this game Questions []QuestionData // An array of the questions for this game @@ -73,7 +74,7 @@ func Get(identifier Identifier) *Game { // New Creates a new game instance with the provided host, title, and questions. // also starts a new goroutine for the games loop, adds it to Games and returns // a reference to the game -func New(host *net.Connection, title string, questions []QuestionData) *Game { +func New(host *Connection, title string, questions []QuestionData) *Game { id := CreateGameId() // Create a new unique game ID game := Game{ Host: host, @@ -94,7 +95,7 @@ func New(host *net.Connection, title string, questions []QuestionData) *Game { // Join adds a new player to the game with the provided connection and name // and returns a reference to the player -func (game *Game) Join(conn *net.Connection, name string) *Player { +func (game *Game) Join(conn *Connection, name string) *Player { player := game.Players.Create(conn, name) // Create a new player // Send the initial state of the game player.Net.Send(net.GameStatePacket(game.State)) @@ -115,7 +116,7 @@ func (game *Game) IsNameTaken(name string) bool { } // Broadcast sends the provided packet to all the players in the game -func (game *Game) Broadcast(packet net.Packet, host bool) { +func (game *Game) Broadcast(packet Packet, host bool) { // Iterate over all the players game.Players.ForEach(func(id Identifier, player *Player) { player.Net.Send(packet) // Send the packet to the player @@ -129,7 +130,7 @@ func (game *Game) Broadcast(packet net.Packet, host bool) { // BroadcastExcluding sends the provided packet to all the players in the game // excluding any players that match the excluded id. The host parameter determines // whether this packet will also be sent to the host of the game -func (game *Game) BroadcastExcluding(exclude Identifier, packet net.Packet, host bool) { +func (game *Game) BroadcastExcluding(exclude Identifier, packet Packet, host bool) { // Iterate over all the players game.Players.ForEach(func(id Identifier, player *Player) { if id != exclude { // If the player id != the excluded id diff --git a/backend/game/player.go b/backend/game/player.go index 2707c23..aae55e5 100644 --- a/backend/game/player.go +++ b/backend/game/player.go @@ -3,6 +3,7 @@ package game import ( "backend/net" . "backend/tools" + "github.com/jacobtread/gowsps" "sync" "time" ) @@ -10,7 +11,7 @@ import ( type ( // Player A structure representing a player in the game Player struct { - Net *net.Connection // The connection to the player socket + Net *gowsps.Connection // The connection to the player socket Id Identifier // The unique ID of this player Name string // The name of this player Score uint32 // The score this player has @@ -78,7 +79,7 @@ func (store *PlayerStore) CreatePlayerId() Identifier { // Create a new player and add it to the PlayerStore. Sends the player // data of all other players in the game to that player and adds them to // player map. Returns a pointer to the created player -func (store *PlayerStore) Create(conn *net.Connection, name string) *Player { +func (store *PlayerStore) Create(conn *gowsps.Connection, name string) *Player { id := store.CreatePlayerId() // Create a unique player ID player := Player{ Net: conn, // Set the net connection diff --git a/backend/go.mod b/backend/go.mod index a044b79..59244f3 100644 --- a/backend/go.mod +++ b/backend/go.mod @@ -2,27 +2,9 @@ module backend go 1.18 -require ( - github.com/gin-gonic/gin v1.7.7 - github.com/gorilla/websocket v1.4.2 - github.com/mitchellh/mapstructure v1.4.3 -) +require github.com/jacobtread/gowsps v0.0.0-20220307042916-78f2facec237 require ( - github.com/gin-contrib/sse v0.1.0 // indirect - github.com/go-playground/locales v0.14.0 // indirect - github.com/go-playground/universal-translator v0.18.0 // indirect - github.com/go-playground/validator/v10 v10.10.0 // indirect - github.com/golang/protobuf v1.5.2 // indirect - github.com/json-iterator/go v1.1.12 // indirect - github.com/leodido/go-urn v1.2.1 // indirect - github.com/mattn/go-isatty v0.0.14 // indirect - github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect - github.com/modern-go/reflect2 v1.0.2 // indirect - github.com/ugorji/go/codec v1.2.6 // indirect - golang.org/x/crypto v0.0.0-20220213190939-1e6e3497d506 // indirect - golang.org/x/sys v0.0.0-20220209214540-3681064d5158 // indirect - golang.org/x/text v0.3.7 // indirect - google.golang.org/protobuf v1.27.1 // indirect - gopkg.in/yaml.v2 v2.4.0 // indirect + github.com/gorilla/websocket v1.5.0 // indirect + github.com/mitchellh/mapstructure v1.4.3 // indirect ) diff --git a/backend/go.sum b/backend/go.sum index 08f1a66..fe12757 100644 --- a/backend/go.sum +++ b/backend/go.sum @@ -1,112 +1,6 @@ -github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= -github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= -github.com/gin-gonic/gin v1.7.7 h1:3DoBmSbJbZAWqXJC3SLjAPfutPJJRN1U5pALB7EeTTs= -github.com/gin-gonic/gin v1.7.7/go.mod h1:axIBovoeJpVj8S3BwE0uPMTeReE4+AfFtqpqaZ1qq1U= -github.com/go-playground/assert/v2 v2.0.1 h1:MsBgLAaY856+nPRTKrp3/OZK38U/wa0CcBYNjji3q3A= -github.com/go-playground/assert/v2 v2.0.1/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4= -github.com/go-playground/locales v0.13.0/go.mod h1:taPMhCMXrRLJO55olJkUXHZBHCxTMfnGwq/HNwmWNS8= -github.com/go-playground/locales v0.14.0 h1:u50s323jtVGugKlcYeyzC0etD1HifMjqmJqb8WugfUU= -github.com/go-playground/locales v0.14.0/go.mod h1:sawfccIbzZTqEDETgFXqTho0QybSa7l++s0DH+LDiLs= -github.com/go-playground/universal-translator v0.17.0/go.mod h1:UkSxE5sNxxRwHyU+Scu5vgOQjsIJAF8j9muTVoKLVtA= -github.com/go-playground/universal-translator v0.18.0 h1:82dyy6p4OuJq4/CByFNOn/jYrnRPArHwAcmLoJZxyho= -github.com/go-playground/universal-translator v0.18.0/go.mod h1:UvRDBj+xPUEGrFYl+lu/H90nyDXpg0fqeB/AQUGNTVA= -github.com/go-playground/validator/v10 v10.4.1/go.mod h1:nlOn6nFhuKACm19sB/8EGNn9GlaMV7XkbRSipzJ0Ii4= -github.com/go-playground/validator/v10 v10.10.0 h1:I7mrTYv78z8k8VXa/qJlOlEXn/nBh+BF8dHX5nt/dr0= -github.com/go-playground/validator/v10 v10.10.0/go.mod h1:74x4gJWsvQexRdW8Pn3dXSGrTK4nAUsbPlLADvpJkos= -github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= -github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= -github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= -github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= -github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -github.com/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= -github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= -github.com/json-iterator/go v1.1.9/go.mod h1:KdQUCv79m/52Kvf8AW2vK1V8akMuk1QjK/uOdHXbAo4= -github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= -github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= -github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= -github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= -github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= -github.com/leodido/go-urn v1.2.0/go.mod h1:+8+nEpDfqqsY+g338gtMEUOtuK+4dEMhiQEgxpxOKII= -github.com/leodido/go-urn v1.2.1 h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w= -github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY= -github.com/mattn/go-isatty v0.0.12/go.mod h1:cbi8OIDigv2wuxKPP5vlRcQ1OAZbq2CE4Kysco4FUpU= -github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y= -github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94= +github.com/gorilla/websocket v1.5.0 h1:PPwGk2jz7EePpoHN/+ClbZu8SPxiqlu12wZP/3sWmnc= +github.com/gorilla/websocket v1.5.0/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/jacobtread/gowsps v0.0.0-20220307042916-78f2facec237 h1:Tpen12Z9R8yj6kx6k33eyS1YjhYDww7zVEvL/mALxSs= +github.com/jacobtread/gowsps v0.0.0-20220307042916-78f2facec237/go.mod h1:c5mgiL42WSK+yA2ywY9hxcrk2frxh0nnhSuwncIjs2Q= github.com/mitchellh/mapstructure v1.4.3 h1:OVowDSCllw/YjdLkam3/sm7wEtOy59d8ndGgCcyj8cs= github.com/mitchellh/mapstructure v1.4.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v0.0.0-20180701023420-4b7aa43c6742/go.mod h1:bx2lNnkwVCuqBIxFjflWJWanXIb3RllmbCylyMrvgv0= -github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= -github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= -github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= -github.com/rogpeppe/go-internal v1.6.1/go.mod h1:xXDCJY+GAPziupqXw64V24skbSoqbTEfhy4qGm1nDQc= -github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= -github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= -github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= -github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= -github.com/ugorji/go v1.1.7/go.mod h1:kZn38zHttfInRq0xu/PH0az30d+z6vm202qpg1oXVMw= -github.com/ugorji/go v1.2.6/go.mod h1:anCg0y61KIhDlPZmnH+so+RQbysYVyDko0IMgJv0Nn0= -github.com/ugorji/go/codec v1.1.7/go.mod h1:Ax+UKWsSmolVDwsd+7N3ZtXu+yMGCf907BLYF3GoBXY= -github.com/ugorji/go/codec v1.2.6 h1:7kbGefxLoDBuYXOms4yD7223OpNMMPNPZxXk5TvFcyQ= -github.com/ugorji/go/codec v1.2.6/go.mod h1:V6TCNZ4PHqoHGFZuSG1W8nrCzzdgA2DozYxWFFpvxTw= -golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= -golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= -golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= -golang.org/x/crypto v0.0.0-20220213190939-1e6e3497d506 h1:EuGTJDfeg/PGZJp3gq1K+14eSLFTsrj1eg8KQuiUyKg= -golang.org/x/crypto v0.0.0-20220213190939-1e6e3497d506/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= -golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= -golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= -golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= -golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20200116001909-b77594299b42/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= -golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20210806184541-e5e7981a1069/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.0.0-20220209214540-3681064d5158 h1:rm+CHSpPEEW2IsXUib1ThaHIjuBVZjxNgSKmBLFfD4c= -golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= -golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= -golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= -golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk= -golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= -golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= -golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= -google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= -google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -google.golang.org/protobuf v1.27.1 h1:SnqbnDw1V7RiZcXPx5MEeqPv2s79L9i7BJUlG/+RurQ= -google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= -gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= -gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= -gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI= -gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.8/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= -gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= -gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= -gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo= -gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/backend/net/client.go b/backend/net/client.go index c668a44..42c9656 100644 --- a/backend/net/client.go +++ b/backend/net/client.go @@ -6,13 +6,13 @@ import ( // Ids for client packets const ( - CCreateGame PacketId = 0x00 - CCheckNameTaken = 0x01 - CRequestGameState = 0x02 - CRequestJoin = 0x03 - CStateChange = 0x04 - CAnswer = 0x05 - CKick = 0x06 + CCreateGame int = 0x00 + CCheckNameTaken = 0x01 + CRequestGameState = 0x02 + CRequestJoin = 0x03 + CStateChange = 0x04 + CAnswer = 0x05 + CKick = 0x06 ) type StateChangeId = uint8 diff --git a/backend/net/net.go b/backend/net/net.go deleted file mode 100644 index 7676cbc..0000000 --- a/backend/net/net.go +++ /dev/null @@ -1,84 +0,0 @@ -package net - -import ( - "github.com/gorilla/websocket" - "github.com/mitchellh/mapstructure" - "log" - "sync" -) - -type ( - - // PacketId All packet ids are represented as 16-bit integers - PacketId = uint16 - - // PacketData All data for packets is of type interface{} as a - // placeholder for its real struct - PacketData interface{} - - // RawPacket The type of data raw packets are parsed into (a string -> interface map) - RawPacket map[string]interface{} - - // RawPacketData The type of data raw packets contents are parsed into (a string -> interface map) - RawPacketData map[string]interface{} - - // Packet The structure for outbound packets - Packet struct { - Id PacketId `json:"id"` - Data PacketData `json:"data,omitempty"` - } - - // PacketRaw The structure for inbound packets only used for outbound - // packets in this case though - PacketRaw struct { - Id PacketId `json:"id"` - Data RawPacketData `json:"data,omitempty"` - } - - // Connection represents a connection to a websocket has extension function - // for doing actions such as sending packets - Connection struct { - Open bool // Whether the connection is still open or not - Socket *websocket.Conn // The connection to the socket - Lock *sync.RWMutex // Write lock for the - } -) - -// NewConnection Creates a new connection struct and sets the close handler -func NewConnection(ws *websocket.Conn) *Connection { - // Create the new connection - conn := Connection{Socket: ws, Open: true, Lock: &sync.RWMutex{}} - ws.SetCloseHandler(func(code int, text string) error { - // Set the connection open to false - conn.Open = false - return nil - }) - // Return the connection pointer - return &conn -} - -// Send will send the provided packet to the connection socket -func (conn *Connection) Send(packet Packet) { - if conn.Open { // Only send the packet if the connection is open - conn.Lock.Lock() - // Write the packet to the socket as JSON - _ = conn.Socket.WriteJSON(packet) - conn.Lock.Unlock() - } -} - -// HandlePacket wraps around the packet data to create a type safe decoding -// from the packet data map to the packet struct -func HandlePacket[T interface{}](rawPacket PacketRaw, action func(data *T)) { - d := rawPacket.Data - if d != nil { - out := new(T) - err := mapstructure.Decode(d, out) - if err != nil { - log.Panic(err) - } - action(out) - } else { - log.Printf("Packet with id '%x' expected data but recieved none", rawPacket.Id) - } -} diff --git a/backend/net/server.go b/backend/net/server.go index edfb280..abee14e 100644 --- a/backend/net/server.go +++ b/backend/net/server.go @@ -2,21 +2,22 @@ package net import ( "backend/tools" + . "github.com/jacobtread/gowsps" "time" ) // Ids for server packets const ( - SDisconnect PacketId = 0x00 - SError = 0x01 - SJoinedGame = 0x02 - SNameTakenResult = 0x03 - SGameState = 0x04 - SPlayerData = 0x05 - STimeSync = 0x06 - SQuestion = 0x07 - SAnswerResult = 0x08 - SScores = 0x09 + SDisconnect int = 0x00 + SError = 0x01 + SJoinedGame = 0x02 + SNameTakenResult = 0x03 + SGameState = 0x04 + SPlayerData = 0x05 + STimeSync = 0x06 + SQuestion = 0x07 + SAnswerResult = 0x08 + SScores = 0x09 ) // DisconnectPacket creates a new disconnect packet with the provided reason