### Start the Gateway Service Source: https://pkg.go.dev/github.com/aluka-7/game-gateway Launches the game gateway service. Ensure all configurations are set up before running. ```bash go run . ``` -------------------------------- ### Start Gateway Command Source: https://pkg.go.dev/github.com/aluka-7/game-gateway Command to start the main gateway service. ```bash # Start the gateway go run . ``` -------------------------------- ### Web Server Configuration Example Source: https://pkg.go.dev/github.com/aluka-7/game-gateway Configures the web server address and logging for the gateway service. This configuration is stored at /system/base/server/10000. ```json { "addr" : ":9006", "enableLog" : true } ``` -------------------------------- ### Run TCP Server Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/tcp Starts the TCP server's main loop, handling incoming connections and messages. ```go func (ts *TcpServer) Run() ``` -------------------------------- ### TCP Server Configuration Example Source: https://pkg.go.dev/github.com/aluka-7/game-gateway Configures the connection entry point for game services (internal communication). This configuration is stored at /system/base/server/tcp/10000. ```json { "addr": ":9800" } ``` -------------------------------- ### WebSocket Server Configuration Example Source: https://pkg.go.dev/github.com/aluka-7/game-gateway Sets the client connection address for WebSocket. This configuration is stored at /system/base/server/ws/10000. ```json { "addr": "tcp://:9009" } ``` -------------------------------- ### Gateway Service Configuration Example Source: https://pkg.go.dev/github.com/aluka-7/game-gateway Defines the list of allowed game services (TCP) that the gateway can forward traffic to. This configuration is stored at /system/app/game/gateway. ```json { "gameList": ["wingo"] } ``` -------------------------------- ### WebSocket Authentication Message Example Source: https://pkg.go.dev/github.com/aluka-7/game-gateway Example of the 'system/auth' message format required for WebSocket authentication. The token must be prefixed with 'Bearer '. ```json { "server": "system", "event": "auth", "seq": 1740000000, "data": { "token": "Bearer " } } ``` -------------------------------- ### Redis Cache Configuration Example Source: https://pkg.go.dev/github.com/aluka-7/game-gateway Configures the Redis cache provider, including host, port, database, and password. This configuration is stored at /system/base/cache/10000. ```json { "provider": "redis", "database": "0", "ping": "true", "host": "127.0.0.1", "port": "6379", "password": "123456" } ``` -------------------------------- ### Manager Get Method Signature Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/conn Method signature for retrieving a client by its user ID from the manager. ```go func (m *Manager) Get(uid int64) (*Client, bool) ``` -------------------------------- ### Get User Token Key Function Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/dto Generates a unique key for a user token based on the provided user ID. ```go func GetUserTokenKey(userId int64) string ``` -------------------------------- ### Initialize Router Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/router Creates and returns a new instance of Router. ```go func NewRouter() *Router ``` -------------------------------- ### Initialize WebSocket Codec Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/ws Creates a new instance of the WebSocket codec. ```go func NewWsCodec() *wsCodec ``` -------------------------------- ### Create WebSocket Server Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/ws Initializes a new WebSocket server with the provided configuration, cache provider, and TCP address. ```go func NewWsServer(cfg *dto.GatewayConfig, ce cache.Provider, tcpAddr string) gnet.EventHandler ``` -------------------------------- ### Initialize WebSocket Server Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/wire Initializes a new WebSocket event handler using the provided gateway configuration, cache provider, and string parameter. ```go func InitializeWsServer(gatewayConfig *dto.GatewayConfig, provider cache.Provider, string2 string) gnet.EventHandler ``` -------------------------------- ### Create New TCP Server Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/tcp Creates and initializes a new TcpServer. Requires the server address, a cache provider, a list of games, and channels for incoming and outgoing messages. ```go func NewTcpServer(addr string, ce cache.Provider, gameList []string, inMsg <-chan *dto.CommonReq, outMsg chan<- *dto.CommonRes) *TcpServer ``` -------------------------------- ### func InitializeWsServer Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/wire Initializes the WebSocket server using the provided gateway configuration, cache provider, and string identifier. ```APIDOC ## func InitializeWsServer ### Description Initializes a new WebSocket server instance for the game gateway. ### Parameters - **gatewayConfig** (*dto.GatewayConfig) - Required - Configuration object for the gateway. - **provider** (cache.Provider) - Required - Cache provider instance. - **string2** (string) - Required - Identifier string. ### Returns - **gnet.EventHandler** - Returns an event handler for the initialized WebSocket server. ``` -------------------------------- ### NewClient Function Signature Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/conn Function signature for creating a new Client instance. ```go func NewClient(uid int64, conn gnet.Conn) *Client ``` -------------------------------- ### Configure UAF via Environment Variable Source: https://pkg.go.dev/github.com/aluka-7/game-gateway Sets the UAF (User Authentication Framework) configuration by exporting the generated ciphertext as an environment variable. This is the recommended method for setting up authentication. ```bash export UAF="your ciphertext" ``` -------------------------------- ### Run WebSocket Client Source: https://pkg.go.dev/github.com/aluka-7/game-gateway Executes the WebSocket client utility for testing. This is typically found in the cmd/ws-client directory. ```bash go run ./cmd/ws-client ``` -------------------------------- ### Run WS Test Client Command Source: https://pkg.go.dev/github.com/aluka-7/game-gateway Command to run the WebSocket test client. ```bash # Run the WS test client go run ./cmd/ws-client ``` -------------------------------- ### Architecture Diagram Source: https://pkg.go.dev/github.com/aluka-7/game-gateway Illustrates the basic architecture of the game gateway, showing the flow from client WebSocket connections to the game server via TCP forwarding. ```text [ Client ] │ WebSocket ▼ [ Gateway ] │ TCP ▼ [ Game Server ] ``` -------------------------------- ### Run TCP Client Source: https://pkg.go.dev/github.com/aluka-7/game-gateway Executes the TCP client utility for testing. This is typically found in the cmd/tcp-client directory. ```bash go run ./cmd/tcp-client ``` -------------------------------- ### Run TCP Test Client Command Source: https://pkg.go.dev/github.com/aluka-7/game-gateway Command to run the TCP test client. ```bash # Run the TCP test client go run ./cmd/tcp-client ``` -------------------------------- ### Router Type and Methods Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/router Documentation for the Router type, including its constructor and methods for message handling and registration. ```APIDOC ## Type: Handler ### Description Represents a function that handles incoming messages. ### Type Definition ```go type Handler func(uid int64, data []byte) ``` ## Type: Router ### Description Manages message routing and handler registration. ### Type Definition ```go type Router struct { // contains filtered or unexported fields } ``` ## Function: NewRouter ### Description Creates and returns a new instance of the Router. ### Signature ```go func NewRouter() *Router ``` ## Method: (*Router) Handle ### Description Handles an incoming message by dispatching it to the appropriate registered handler. ### Signature ```go func (r *Router) Handle(uid int64, msgId uint16, data []byte) ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```json { "uid": 12345, "msgId": 101, "data": "aGVsbG8gd29ybGQ=" } ``` ### Response #### Success Response (200) - None #### Response Example ```json { "status": "handled" } ``` ## Method: (*Router) Register ### Description Registers a handler function for a specific message ID. ### Signature ```go func (r *Router) Register(msgId uint16, h Handler) ``` ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - None ### Request Example ```json { "msgId": 101, "handler": "myMessageHandler" } ``` ### Response #### Success Response (200) - None #### Response Example ```json { "status": "registered" } ``` ``` -------------------------------- ### Define Gateway Structure Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/dto Represents the gateway configuration and path. ```go type Gateway struct { Path string Config GatewayConfig } ``` -------------------------------- ### Define WsConfig Structure Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/dto Configuration for WebSocket service address. ```go type WsConfig struct { Addr string `json:"addr"` } ``` -------------------------------- ### Define UserTokenKey Constant Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/dto Defines the format string used for generating user token keys. ```go const ( UserTokenKey = "system:user:token:%d" ) ``` -------------------------------- ### Gateway Changed Method Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/dto Handles changes in the gateway data. ```go func (b *Gateway) Changed(data map[string]string) ``` -------------------------------- ### Define TcpConfig Structure Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/dto Configuration for TCP service address. ```go type TcpConfig struct { Addr string `json:"addr"` } ``` -------------------------------- ### Manager Snapshot Method Signature Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/conn Method signature for obtaining a snapshot of current connections for safe iteration outside of the manager's lock. ```go func (m *Manager) Snapshot() []ConnItem ``` -------------------------------- ### Server Event Handlers Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/ws Methods for handling various lifecycle events of the WebSocket server. ```go func (w *Server) OnBoot(eng gnet.Engine) gnet.Action ``` ```go func (w *Server) OnClose(c gnet.Conn, err error) gnet.Action ``` ```go func (w *Server) OnOpen(c gnet.Conn) (out []byte, action gnet.Action) ``` ```go func (w *Server) OnShutdown(eng gnet.Engine) ``` ```go func (w *Server) OnTick() (delay time.Duration, action gnet.Action) ``` ```go func (w *Server) OnTraffic(c gnet.Conn) gnet.Action ``` -------------------------------- ### Generate UAF Configuration Source: https://pkg.go.dev/github.com/aluka-7/game-gateway Encrypts configuration strings using a provided key for secure storage. Ensure the key and source string are correctly defined. ```go key := configuration.DesKey src := "{\"backend\":\"127.0.0.1:2181\",\"username\":\"guest\",\"password\":\"guest\"}" enc, _ := utils.Encrypt([]byte(src), []byte(key)) cipher := base64.URLEncoding.EncodeToString(enc) fmt.Println("ciphertext:", cipher) ``` -------------------------------- ### Manager Set Method Signature Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/conn Method signature for setting or updating a client in the manager, associated with a user ID. ```go func (m *Manager) Set(uid int64, c *Client) ``` -------------------------------- ### Client Struct Definition Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/conn Defines the structure for a client connection, including user ID, gnet connection, send channel, and last heartbeat timestamp. ```go type Client struct { UID int64 Conn gnet.Conn Send chan []byte LastHeartbeat int64 // 最后心跳时间戳 } ``` -------------------------------- ### Define Server System Constant Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/ws Constant identifying the system-level server identifier. ```go const ( ServerSystem = "system" ) ``` -------------------------------- ### Define File Descriptor Variable Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/tcp/proto Represents the file descriptor for the tcp_message.proto file. ```go var File_tcp_message_proto protoreflect.FileDescriptor ``` -------------------------------- ### Define GatewayConfig Structure Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/dto Configuration structure for the gateway, including a list of games. ```go type GatewayConfig struct { GameList []string `json:"gameList"` } ``` -------------------------------- ### Configure UAF via File Source: https://pkg.go.dev/github.com/aluka-7/game-gateway Saves the UAF configuration ciphertext to a file named 'configuration.uaf'. This method is an alternative to using environment variables. ```bash echo "your ciphertext" > configuration.uaf ``` -------------------------------- ### WebSocket Server Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/ws Handles the lifecycle and events of the WebSocket server. ```APIDOC ## Function: NewWsServer ### Description Initializes and returns a new WebSocket server event handler. ### Parameters - **cfg** (*dto.GatewayConfig) - Configuration for the gateway. - **ce** (cache.Provider) - Cache provider instance. - **tcpAddr** (string) - The TCP address for the server to listen on. ### Signature ```go func NewWsServer(cfg *dto.GatewayConfig, ce cache.Provider, tcpAddr string) gnet.EventHandler ``` ``` ```APIDOC ## Type: Server ### Description Represents the WebSocket server, implementing gnet.EventHandler. ### Methods #### OnBoot ```go func (w *Server) OnBoot(eng gnet.Engine) gnet.Action ``` Called when the server engine boots up. #### OnClose ```go func (w *Server) OnClose(c gnet.Conn, err error) gnet.Action ``` Called when a connection is closed. #### OnOpen ```go func (w *Server) OnOpen(c gnet.Conn) (out []byte, action gnet.Action) ``` Called when a new connection is opened. #### OnShutdown ```go func (w *Server) OnShutdown(eng gnet.Engine) ``` Called when the server engine shuts down. #### OnTick ```go func (w *Server) OnTick() (delay time.Duration, action gnet.Action) ``` Called periodically for server ticking. #### OnTraffic ```go func (w *Server) OnTraffic(c gnet.Conn) gnet.Action ``` Called when traffic is received on a connection. ``` -------------------------------- ### Define WebSocket Event Constants Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/ws Constants representing standard WebSocket event types used within the package. ```go const ( EventAuth = "auth" EventPing = "ping" EventPong = "pong" ) ``` -------------------------------- ### TcpServer Management Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/tcp Manages TCP server instances, including creation, running, and stopping. ```APIDOC ## TcpServer ### NewTcpServer Creates a new TCP server instance. ### Method func ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **addr** (string) - The address to bind the server to. - **ce** (cache.Provider) - The cache provider to use. - **gameList** ([]string) - A list of games supported by the server. - **inMsg** (<-chan *dto.CommonReq) - Channel for incoming messages. - **outMsg** (chan<- *dto.CommonRes) - Channel for outgoing messages. ### Request Example None ### Response #### Success Response (200) - **TcpServer** (*TcpServer*) - A pointer to the newly created TcpServer. #### Response Example None ### Run Starts the TCP server and begins processing messages. ### Method func (ts *TcpServer) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ### Stop Stops the TCP server. ### Method func (ts *TcpServer) ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### Functions Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/dto Utility functions available in the package. ```APIDOC ## Functions ### GetUserTokenKey `func GetUserTokenKey(userId int64) string` This function generates a unique key for a user's token based on their user ID. It utilizes the `UserTokenKey` constant for formatting. ``` -------------------------------- ### User and UserClaims Definitions Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/ws Structures for representing user data and JWT claims. ```go type User struct { Id int64 `json:"id"` } ``` ```go type UserClaims struct { User User jwt.RegisteredClaims } ``` -------------------------------- ### Define SystemId Constant Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/wire Defines the constant identifier for the system. ```go const ( SystemId = "10000" ) ``` -------------------------------- ### Client Structure Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/conn Definition of the Client object used to track individual connection state. ```APIDOC ## Client Struct ### Description Represents an active connection in the gateway. ### Fields - **UID** (int64): Unique identifier for the client. - **Conn** (gnet.Conn): The underlying network connection. - **Send** (chan []byte): Channel for outgoing messages. - **LastHeartbeat** (int64): Timestamp of the last received heartbeat. ``` -------------------------------- ### Pack Function Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/protocol Use this function to pack a message with a specified message ID and body. It returns the packed byte slice. ```go func Pack(msgId uint16, body []byte) []byte ``` -------------------------------- ### Define Handler Type Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/router Defines the function signature for message handlers. ```go type Handler func(uid int64, data []byte) ``` -------------------------------- ### Handle Incoming Messages Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/router Dispatches a message to the appropriate handler based on the message ID. ```go func (r *Router) Handle(uid int64, msgId uint16, data []byte) ``` -------------------------------- ### Server Struct Definition Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/ws The primary server structure embedding the gnet event engine. ```go type Server struct { gnet.BuiltinEventEngine // contains filtered or unexported fields } ``` -------------------------------- ### func Pack Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/protocol Serializes a message ID and body into a byte slice for network transmission. ```APIDOC ## func Pack ### Description Serializes a message ID and body into a byte slice for network transmission. ### Parameters - **msgId** (uint16) - Required - The identifier for the message. - **body** ([]byte) - Required - The payload data to be packed. ### Response - **Returns** ([]byte) - The serialized byte slice containing the message ID and body. ``` -------------------------------- ### Data Structures Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/dto Defines the data structures used for requests, responses, and configuration. ```APIDOC ## Types ### AuthReq `type AuthReq struct { Token string `json:"token"` }` Represents an authentication request, containing a single field for the authentication token. ``` ```APIDOC ### CommonReq `type CommonReq struct { Server string `json:"server"` Event string `json:"event"` Seq int64 `json:"seq"` UserId int64 `json:"userId,omitempty"` Data json.RawMessage `json:"data,omitempty"` }` Represents a common request structure used for communication. It includes fields for the server, event type, sequence number, user ID, and arbitrary data. ``` ```APIDOC ### CommonRes `type CommonRes struct { Server string `json:"server"` Event string `json:"event"` Seq int64 `json:"seq,omitempty"` UserId int64 `json:"userId,omitempty"` Code int `json:"code"` Msg string `json:"msg,omitempty"` Data json.RawMessage `json:"data,omitempty"` }` Represents a common response structure. It includes fields for the server, event type, sequence number, user ID, status code, message, and optional data. This structure is used for messages sent to clients. ``` ```APIDOC ### Gateway `type Gateway struct { Path string Config GatewayConfig }` Represents the main gateway structure, holding its path and configuration. ``` ```APIDOC ### GatewayConfig `type GatewayConfig struct { GameList []string `json:"gameList"` }` Configuration for the gateway, including a list of games it manages. ``` ```APIDOC ### TcpConfig `type TcpConfig struct { Addr string `json:"addr"` }` Configuration for TCP connections, specifying the address. ``` ```APIDOC ### WsConfig `type WsConfig struct { Addr string `json:"addr"` }` Configuration for WebSocket connections, specifying the address. ``` -------------------------------- ### Gateway Methods Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/dto Methods associated with the Gateway type. ```APIDOC ## Gateway Methods ### Changed `func (b *Gateway) Changed(data map[string]string)` This method is part of the `Gateway` type. It likely handles changes or updates to the gateway's state or configuration, taking a map of string key-value pairs as input. ``` -------------------------------- ### Manager API Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/conn Methods for managing client connections within the gateway. ```APIDOC ## Manager Methods ### Description The Manager handles the lifecycle and storage of client connections identified by a unique UID. ### Methods - **NewManager() *Manager**: Initializes a new connection manager. - **Get(uid int64) (*Client, bool)**: Retrieves a client by UID. Returns the client and a boolean indicating if it was found. - **Set(uid int64, c *Client)**: Adds or updates a client in the manager. - **Remove(uid int64)**: Removes a client from the manager by UID. - **Range(fn func(uid int64, cli *Client))**: Iterates over all managed clients using the provided function. - **Snapshot() []ConnItem**: Returns a slice of ConnItem representing a point-in-time copy of all connections. ``` -------------------------------- ### TcpMessage Method Definitions Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/tcp/proto Utility methods for accessing fields and managing the state of a TcpMessage instance. ```go func (*TcpMessage) Descriptor() ([]byte, []int) ``` ```go func (x *TcpMessage) GetCode() int32 ``` ```go func (x *TcpMessage) GetData() []byte ``` ```go func (x *TcpMessage) GetEvent() string ``` ```go func (x *TcpMessage) GetMsg() string ``` ```go func (x *TcpMessage) GetSeq() int64 ``` ```go func (x *TcpMessage) GetServer() string ``` ```go func (x *TcpMessage) GetUserId() int64 ``` ```go func (*TcpMessage) ProtoMessage() ``` ```go func (x *TcpMessage) ProtoReflect() protoreflect.Message ``` ```go func (x *TcpMessage) Reset() ``` ```go func (x *TcpMessage) String() string ``` -------------------------------- ### Define Router Struct Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/router Represents the router structure containing internal routing logic. ```go type Router struct { // contains filtered or unexported fields } ``` -------------------------------- ### Define AuthReq Structure Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/dto Represents the authentication request containing a token. ```go type AuthReq struct { Token string `json:"token"` } ``` -------------------------------- ### TCP Server Type Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/tcp Represents a TCP server instance. It manages connections and message handling. ```go type TcpServer struct { // contains filtered or unexported fields } ``` -------------------------------- ### Intercept Authentication Header Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/ws Parses and validates authentication headers to return user claims. ```go func Intercept(ce cache.Provider, authHeader string) *UserClaims ``` -------------------------------- ### NewManager Function Signature Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/conn Function signature for creating a new Manager instance. ```go func NewManager() *Manager ``` -------------------------------- ### Manager Range Method Signature Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/conn Method signature for iterating over all clients managed by the Manager, applying a function to each client. ```go func (m *Manager) Range(fn func(uid int64, cli *Client)) ``` -------------------------------- ### Constants Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/dto Defines constants used within the package. ```APIDOC ## Constants ### UserTokenKey `const UserTokenKey = "system:user:token:%d"` This constant is used as a key format for storing user tokens in a system, likely a cache or database. The `%d` placeholder is intended for a user ID. ``` -------------------------------- ### User and Authentication Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/ws Defines user-related types and an authentication interceptor. ```APIDOC ## Type: User ### Description Represents a user with an ID. ### Fields - **Id** (int64) - The unique identifier for the user. ### JSON Structure ```json { "id": 12345 } ``` ``` ```APIDOC ## Type: UserClaims ### Description Contains user claims, including user information and registered JWT claims. ### Fields - **User** (User) - The user object. - **RegisteredClaims** (jwt.RegisteredClaims) - Standard JWT claims. ``` ```APIDOC ## Function: Intercept ### Description Intercepts requests to extract user claims based on authentication headers. ### Parameters - **ce** (cache.Provider) - Cache provider for potential caching of claims. - **authHeader** (string) - The authentication header from the request. ### Returns - (*UserClaims) - The extracted user claims, or nil if authentication fails. ``` -------------------------------- ### Define CommonReq Structure Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/dto Represents a standard request structure used for communication. ```go type CommonReq struct { Server string `json:"server"` // 服务 Event string `json:"event"` // 事件 Seq int64 `json:"seq"` // 请求id UserId int64 `json:"userId,omitempty"` // 用户id Data json.RawMessage `json:"data,omitempty"` // 数据 } ``` -------------------------------- ### Manager Struct Definition Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/conn Defines the Manager struct, which is used for managing client connections. It contains unexported fields. ```go type Manager struct { // contains filtered or unexported fields } ``` -------------------------------- ### ConnItem Struct Definition Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/conn Defines a structure used for snapshotting connection items, containing a user ID and a pointer to the Client. ```go type ConnItem struct { UID int64 Client *Client } ``` -------------------------------- ### Access the global SugaredLogger Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/utils/logger Use the exported Log variable to access the zap.SugaredLogger instance. ```go var Log *zap.SugaredLogger ``` -------------------------------- ### WebSocket Constants Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/ws Defines constants used for WebSocket event types and server identification. ```APIDOC ## Constants ### Event Types ```go const ( EventAuth = "auth" EventPing = "ping" EventPong = "pong" ) ``` ### Server Identification ```go const ( ServerSystem = "system" ) ``` ``` -------------------------------- ### Manager Remove Method Signature Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/conn Method signature for removing a client from the manager using its user ID. ```go func (m *Manager) Remove(uid int64) ``` -------------------------------- ### Define CommonRes Structure Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/dto Represents a standard response structure for messages sent to the client. ```go type CommonRes struct { Server string `json:"server"` // 服务名称 Event string `json:"event"` // 客户端事件 Seq int64 `json:"seq,omitempty"` // 请求id UserId int64 `json:"userId,omitempty"` // 用户id,为 0 发给所有人 Code int `json:"code"` // 错误码 Msg string `json:"msg,omitempty"` // 错误信息 Data json.RawMessage `json:"data,omitempty"` // 数据 } ``` -------------------------------- ### WebSocket Codec Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/ws Provides functionality for encoding and decoding WebSocket messages. ```APIDOC ## Function: NewWsCodec ### Description Creates a new WebSocket codec. ### Signature ```go func NewWsCodec() *wsCodec ``` ``` -------------------------------- ### Register Message Handler Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/router Registers a handler function for a specific message ID. ```go func (r *Router) Register(msgId uint16, h Handler) ``` -------------------------------- ### Stop TCP Server Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/tcp Gracefully shuts down the TCP server, closing connections and releasing resources. ```go func (ts *TcpServer) Stop() ``` -------------------------------- ### TCP Functions Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/tcp Provides functions for encoding and decoding data for TCP communication. ```APIDOC ## TCP Functions ### DecodeRes Decodes a byte slice payload into a CommonRes object. ### Method func ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) - ***CommonRes** (*dto.CommonRes*) - The decoded response object. - **error** (*error*) - An error if decoding fails. #### Response Example None ## EncodeFrame Encodes a byte slice body into a frame. ### Method func ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **body** ([]byte) - The data to be encoded. ### Request Example None ### Response #### Success Response (200) - **[]byte** - The encoded frame. #### Response Example None ## EncodeReq Encodes a CommonReq message into a byte slice. ### Method func ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **msg** (*dto.CommonReq*) - The request message to encode. ### Request Example None ### Response #### Success Response (200) - **[]byte** - The encoded request. - **error** (*error*) - An error if encoding fails. #### Response Example None ## ReadFrame Reads a frame from an io.Reader. ### Method func ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **r** (io.Reader) - The reader to read from. ### Request Example None ### Response #### Success Response (200) - **[]byte** - The read frame data. - **error** (*error*) - An error if reading fails. #### Response Example None ``` -------------------------------- ### TcpMessage Structure Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/tcp/proto Defines the fields available in the TcpMessage protocol buffer object. ```APIDOC ## TcpMessage Structure ### Description The TcpMessage struct represents the data model for TCP messages within the gateway. It includes metadata for routing and status reporting. ### Fields - **server** (string) - Identifier for the server. - **event** (string) - The event type associated with the message. - **seq** (int64) - Sequence number for message ordering. - **user_id** (int64) - The ID of the user associated with the message. - **code** (int32) - Status code for the operation. - **msg** (string) - Descriptive message text. - **data** ([]byte) - Raw payload data. ``` -------------------------------- ### Prometheus Metrics Address Source: https://pkg.go.dev/github.com/aluka-7/game-gateway The endpoint where Prometheus metrics are exposed for monitoring the gateway service. ```text http://ip:7070/metrics ``` -------------------------------- ### Read TCP Frame Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/tcp Reads a TCP frame from an io.Reader. This function is responsible for extracting a complete message frame from the input stream. ```go func ReadFrame(r io.Reader) ([]byte, error) ``` -------------------------------- ### Encode TCP Request Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/tcp Encodes a CommonReq message into a byte slice for transmission. Requires a CommonReq object and returns the encoded byte slice or an error. ```go func EncodeReq(msg *dto.CommonReq) ([]byte, error) ``` -------------------------------- ### TcpMessage Struct Definition Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/tcp/proto The primary data structure for TCP messages, containing fields for server, event, sequence, user ID, code, message, and data. ```go type TcpMessage struct { Server string `protobuf:"bytes,1,opt,name=server,proto3" json:"server,omitempty"` Event string `protobuf:"bytes,2,opt,name=event,proto3" json:"event,omitempty"` Seq int64 `protobuf:"varint,3,opt,name=seq,proto3" json:"seq,omitempty"` UserId int64 `protobuf:"varint,4,opt,name=user_id,json=userId,proto3" json:"user_id,omitempty"` Code int32 `protobuf:"varint,5,opt,name=code,proto3" json:"code,omitempty"` Msg string `protobuf:"bytes,6,opt,name=msg,proto3" json:"msg,omitempty"` Data []byte `protobuf:"bytes,7,opt,name=data,proto3" json:"data,omitempty"` // contains filtered or unexported fields } ``` -------------------------------- ### Encode TCP Frame Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/tcp Encodes a byte slice body into a TCP frame. This function is used to prepare data for transmission over TCP. ```go func EncodeFrame(body []byte) []byte ``` -------------------------------- ### Decode TCP Response Source: https://pkg.go.dev/github.com/aluka-7/game-gateway/tcp Decodes a byte slice payload into a CommonRes object. Requires the payload and an alias string. Returns the decoded response or an error. ```go func DecodeRes(payload []byte, alias string) (*dto.CommonRes, error) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.