spark-server/internal/transport/tcp/protocol/payload.go
2026-09-18 14:50:41 +08:00

70 lines
1.4 KiB
Go

package protocol
import (
"encoding/json"
"spark-server/internal/pkg/errs"
"spark-server/internal/pkg/reply"
)
type AuthRequest struct {
Token string `json:"token"`
DeviceID uint64 `json:"device_id"`
AppVersion string `json:"app_version"`
Language string `json:"language"`
}
type AuthResponse struct {
UserID int64 `json:"user_id"`
DeviceID uint64 `json:"device_id"`
}
type MsgIDBody struct {
MsgID int64 `json:"msg_id"`
}
type KickBody struct {
Reason string `json:"reason"`
}
type ErrorBody struct {
Code string
Message string
}
func EncodeAuthRequest(a AuthRequest) []byte {
b, _ := json.Marshal(a)
return b
}
func DecodeAuthRequest(body []byte) (AuthRequest, error) {
var req AuthRequest
if err := json.Unmarshal(body, &req); err != nil {
return AuthRequest{}, errs.ErrInvalidFrame
}
if req.Token == "" {
return AuthRequest{}, errs.ErrInvalidArgument
}
return req, nil
}
func EncodeError(requestID string, e ErrorBody) []byte {
return reply.MustMarshal(reply.StampID(reply.Fail(e.Code, e.Message), requestID))
}
func DecodeError(body []byte) (ErrorBody, error) {
env, err := reply.Unmarshal(body)
if err != nil {
return ErrorBody{}, err
}
return ErrorBody{Code: env.Code, Message: env.Msg}, nil
}
func EncodeMsgID(requestID string, id int64) []byte {
return EncodeOK(requestID, MsgIDBody{MsgID: id})
}
func EncodeKick(requestID, reason string) []byte {
return EncodeOK(requestID, KickBody{Reason: reason})
}