sshpong/internal/lobby/lobby_messages.go

97 lines
1.8 KiB
Go
Raw Normal View History

2024-09-26 19:49:59 -06:00
package lobby
2024-09-28 23:26:06 -06:00
import "encoding/json"
const (
Name = iota
Chat
Invite
PendingInvite
Accept
Accepted
StartGame
Decline
Disconnect
Connect
CurrentlyConnected
Error
2024-09-26 19:49:59 -06:00
)
2024-09-28 23:26:06 -06:00
type NameData struct {
2024-09-26 19:49:59 -06:00
Name string `json:"name"`
}
2024-09-28 23:26:06 -06:00
type ChatData struct {
2024-09-26 19:49:59 -06:00
From string `json:"from"`
Message string `json:"message"`
}
2024-09-28 23:26:06 -06:00
type InviteData struct {
2024-09-26 19:49:59 -06:00
From string `json:"from"`
To string `json:"to"`
}
2024-09-28 23:26:06 -06:00
type PendingInviteData struct {
2024-09-26 19:49:59 -06:00
Recipient string `json:"recipient"`
}
2024-09-28 23:26:06 -06:00
type AcceptData struct {
2024-10-03 22:41:33 -06:00
From string `json:"from"`
To string `json:"to"`
GameID string `json:"gameID"`
2024-09-26 19:49:59 -06:00
}
2024-09-28 23:26:06 -06:00
type AcceptedData struct {
2024-09-26 19:49:59 -06:00
Accepter string `json:"accepter"`
2024-10-03 22:41:33 -06:00
GameID string `json:"gameID"`
2024-09-26 19:49:59 -06:00
}
2024-09-28 23:26:06 -06:00
type StartGameData struct {
2024-09-26 19:49:59 -06:00
To string `json:"to"`
2024-10-03 22:41:33 -06:00
From string `json:"from"`
GameID string `json:"gameID"`
2024-09-26 19:49:59 -06:00
}
2024-09-28 23:26:06 -06:00
type DeclineData struct {
2024-09-26 19:49:59 -06:00
From string `json:"from"`
To string `json:"to"`
}
2024-09-28 23:26:06 -06:00
type DisconnectData struct {
2024-09-26 19:49:59 -06:00
From string `json:"from"`
}
2024-09-28 23:26:06 -06:00
type ConnectData struct {
2024-09-26 19:49:59 -06:00
From string `json:"from"`
}
2024-09-28 23:26:06 -06:00
type CurrentlyConnectedData struct {
Players []string `json:"players"`
}
type ErrorData struct {
2024-09-26 19:49:59 -06:00
Message string `json:"message"`
}
2024-09-28 23:26:06 -06:00
func Unmarshal[T NameData | ChatData | InviteData | PendingInviteData | AcceptData | AcceptedData | StartGameData | DeclineData | DisconnectData | ConnectData | CurrentlyConnectedData | ErrorData](msg []byte) (T, error) {
var d T
err := json.Unmarshal(msg[1:], &d)
2024-09-26 19:49:59 -06:00
if err != nil {
2024-09-28 23:26:06 -06:00
return d, err
2024-09-26 19:49:59 -06:00
}
2024-09-28 23:26:06 -06:00
return d, nil
2024-09-26 19:49:59 -06:00
}
2024-09-28 23:26:06 -06:00
func Marshal[T NameData | ChatData | InviteData | PendingInviteData | AcceptData | AcceptedData | StartGameData | DeclineData | DisconnectData | ConnectData | CurrentlyConnectedData | ErrorData](msg T, header int) ([]byte, error) {
mb, err := json.Marshal(msg)
2024-09-26 19:49:59 -06:00
if err != nil {
2024-09-28 23:26:06 -06:00
return mb, err
2024-09-26 19:49:59 -06:00
}
2024-09-28 23:26:06 -06:00
b := []byte{byte(header)}
b = append(b, mb...)
return b, nil
2024-09-26 19:49:59 -06:00
}