### Network Server Example Source: https://github.com/dobyte/due/blob/main/_autodocs/api-reference.md Example of setting up a network server with handlers for connection, reception, and disconnection events. Used for managing client connections. ```go server := tcp.NewServer() server.OnConnect(func(conn network.Conn) { log.Infof("New connection: %d from %s", conn.ID(), conn.RemoteIP()) conn.Bind(123) // Bind user ID }) server.OnReceive(func(conn network.Conn, data []byte) { // Handle received data }) server.OnDisconnect(func(conn network.Conn) { log.Infof("Connection closed: %d", conn.ID()) }) ``` -------------------------------- ### Install Etcd Configuration Source Source: https://github.com/dobyte/due/blob/main/config/etcd/README-ZH.md Install the Etcd configuration source for Due using go get. ```shell go get -u github.com/dobyte/due/config/etcd/v2@latest ``` -------------------------------- ### Install Etcd Registry Source: https://github.com/dobyte/due/blob/main/registry/etcd/README-ZH.md Install the etcd registry package using go get. ```shell go get github.com/dobyte/due/registry/etcd/v2@latest ``` -------------------------------- ### Install Consul Registry Source: https://github.com/dobyte/due/blob/main/registry/consul/README-ZH.md Install the Consul registry module for Due using go get. ```shell go get github.com/dobyte/due/registry/consul/v2@latest ``` -------------------------------- ### Install Consul Configuration Center Source: https://github.com/dobyte/due/blob/main/config/consul/README-ZH.md Install the Consul configuration center module using go get. ```shell go get -u github.com/dobyte/due/config/consul/v2@latest ``` -------------------------------- ### Minimal Configuration Example Source: https://github.com/dobyte/due/blob/main/_autodocs/configuration.md A basic configuration file including PID, mode, cluster gate/node IDs, and HTTP address. ```toml pid = "./run/due.pid" mode = "debug" [cluster.gate] id = "gate-1" [cluster.node] id = "node-1" [http] addr = ":8080" ``` -------------------------------- ### Attribute Storage Usage Example Source: https://github.com/dobyte/due/blob/main/_autodocs/network-and-protocols.md Demonstrates how to use the Attr interface to set, get, delete, and iterate over custom attributes associated with a network connection. ```go conn.Attr().Set("player_id", 123) conn.Attr().Set("level", 10) if level, ok := conn.Attr().Get("level"); ok { log.Infof("Level: %v", level) } conn.Attr().Del("level") conn.Attr().Visit(func(k, v any) bool { log.Infof("%v: %v", k, v) return true }) ``` -------------------------------- ### Distributed Lock Usage Example Source: https://github.com/dobyte/due/blob/main/_autodocs/api-reference.md Example demonstrating how to acquire a distributed lock, perform critical operations, and then release the lock. Ensure proper error handling and defer release. ```go locker := lock.Make("resource-lock") if err := locker.Acquire(ctx); err != nil { // Handle error return } def locker.Release(ctx) // Critical section ``` -------------------------------- ### Runtime Configuration Updates Source: https://github.com/dobyte/due/blob/main/_autodocs/configuration.md Demonstrates how to get, set, and watch for configuration changes dynamically at runtime using the config package. ```go import "github.com/dobyte/due/v2/config" // Get configuration value := config.Get("some.key").String() // Set configuration (if writable) config.Set("some.key", "new-value") // Watch for changes config.Watch(func(ctx context.Context, cfg *Configuration) error { log.Info("Configuration changed:", cfg) return nil }) ``` -------------------------------- ### Production Configuration Example Source: https://github.com/dobyte/due/blob/main/_autodocs/configuration.md A comprehensive configuration for production environments, including cluster, HTTP, transport, and packet settings. ```toml pid = "./run/due.pid" mode = "release" timezone = "UTC" shutdownMaxWaitTime = "30s" [cluster.gate] id = "gate-prod-1" name = "production-gateway" dispatch = "wrr" addr = ":6000" expose = true connNum = 20 callTimeout = "5s" [cluster.gate.metadata] region = "us-east-1" version = "1.0" [cluster.node] id = "node-prod-1" name = "production-node" codec = "proto" weight = 2 addr = ":6001" connNum = 20 [cluster.node.metadata] region = "us-east-1" [task] size = 200000 nonblocking = true [http] addr = ":8080" certFile = "./certs/server.crt" keyFile = "./certs/server.key" bodyLimit = "10M" concurrency = 100000 [http.cors] enable = true allowOrigins = ["https://app.example.com"] [http.swagger] enable = true [transport.grpc.server] addr = ":50051" expose = true [packet] byteOrder = "big" routeBytes = 2 seqBytes = 2 bufferBytes = 10000 ``` -------------------------------- ### Initialize and Get Configuration Source: https://github.com/dobyte/due/blob/main/_autodocs/configuration.md Demonstrates how to initialize the configuration system and retrieve configuration values using the etc package. Ensure the etc package is imported before use. ```go import "github.com/dobyte/due/v2/etc" // Get configuration value value := etc.Get("cluster.gate.id").String() // Check if key exists if etc.Has("cluster.gate.id") { // Key exists } ``` -------------------------------- ### Create and Start WebSocket Server Source: https://github.com/dobyte/due/blob/main/_autodocs/network-and-protocols.md Sets up a WebSocket server listening on a specific address and path. It includes handlers for connection and data events, compatible with web clients. ```go import "github.com/dobyte/due/v2/network/ws" server := ws.NewServer( ws.WithAddr(":8000"), ws.WithPath("/game"), ) server.OnConnect(func(conn network.Conn) {}) server.OnReceive(func(conn network.Conn, data []byte) {}) server.OnDisconnect(func(conn network.Conn) {}) server.Start() ``` -------------------------------- ### Using Etcd for Configuration Management Source: https://github.com/dobyte/due/blob/main/config/etcd/README-ZH.md Demonstrates how to initialize the Etcd configuration source, store configuration values, and retrieve them. Includes examples of updating configuration and observing changes. ```go package main import ( "context" "github.com/dobyte/due/config/etcd/v2" "github.com/dobyte/due/v2/config" "github.com/dobyte/due/v2/log" "time" ) func main() { // 设置全局配置器 config.SetConfigurator(config.NewConfigurator(config.WithSources(etcd.NewSource()))) ctx := context.Background() filepath := "config.toml" // 更新配置 if err := config.Store(ctx, etcd.Name, filepath, map[string]any{ "timezone": "Local", }); err != nil { log.Errorf("store config failed: %v", err) return } time.Sleep(5 * time.Millisecond) // 读取配置 timezone := config.Get("config.timezone", "UTC").String() log.Infof("timezone: %s", timezone) // 更新配置 if err := config.Store(ctx, etcd.Name, filepath, map[string]any{ "timezone": "UTC", }); err != nil { log.Errorf("store config failed: %v", err) return } time.Sleep(5 * time.Millisecond) // 读取配置 timezone = config.Get("config.timezone", "UTC").String() log.Infof("timezone: %s", timezone) } ``` -------------------------------- ### Registry Connection Example Source: https://github.com/dobyte/due/blob/main/_autodocs/cluster-architecture.md Demonstrates how to establish a connection to a service registry using the Consul client. Ensure the Consul agent is running at the specified address. ```go import "github.com/dobyte/due/v2/registry/consul" registry := consul.NewRegistry( consul.WithAddrs("localhost:8500"), ) gate := gate.NewGate( gate.WithRegistry(registry), ) ``` -------------------------------- ### Consul Configuration Center Usage Example Source: https://github.com/dobyte/due/blob/main/config/consul/README-ZH.md Demonstrates how to initialize the Consul configuration center, store configuration values, and retrieve them. Includes updating configuration and observing changes. ```go package main import ( "context" "github.com/dobyte/due/config/consul/v2" "github.com/dobyte/due/v2/config" "github.com/dobyte/due/v2/log" "time" ) func init() { // 设置全局配置器 config.SetConfigurator(config.NewConfigurator(config.WithSources(consul.NewSource()))) } func main() { var ( ctx = context.Background() file = "config.toml" name = consul.Name ) // 更新配置 if err := config.Store(ctx, name, file, map[string]any{ "timezone": "Local", }); err != nil { log.Errorf("store config failed: %v", err) return } time.Sleep(5 * time.Millisecond) // 读取配置 timezone := config.Get("config.timezone", "UTC").String() log.Infof("timezone: %s", timezone) // 更新配置 if err := config.Store(ctx, name, file, map[string]any{ "timezone": "UTC", }); err != nil { log.Errorf("store config failed: %v", err) return } time.Sleep(5 * time.Millisecond) // 读取配置 timezone = config.Get("config.timezone", "UTC").String() log.Infof("timezone: %s", timezone) } ``` -------------------------------- ### Register Component Hook Source: https://github.com/dobyte/due/blob/main/_autodocs/INDEX.md This snippet shows how to register a hook for a component, specifically for the 'Start' event in the cluster. It allows executing custom logic when a component starts. ```go gate.OnHook(cluster.Start, func(proxy *gate.Proxy) { log.Info("Gate started") }) ``` -------------------------------- ### Define Network Start Handler Function Type Source: https://github.com/dobyte/due/blob/main/_autodocs/types.md Defines the function signature for a handler called when the network server starts. ```go type StartHandler func() ``` -------------------------------- ### Get Process and Host Information with xos Source: https://github.com/dobyte/due/blob/main/_autodocs/utilities.md Retrieve the current process ID and hostname using the xos package. ```Go import "github.com/dobyte/due/v2/utils/xos" // Process information pid := xos.PID() hostname := xos.Hostname() ``` -------------------------------- ### Channel Subscription Example Source: https://github.com/dobyte/due/blob/main/_autodocs/INDEX.md Illustrates a typical flow for channel-based messaging: subscribing to a channel, publishing a message, and delivering it to all subscribers. ```text Subscribe -> Publish -> All Subscribers ``` -------------------------------- ### network.StartHandler Source: https://github.com/dobyte/due/blob/main/_autodocs/types.md Handler function type called when a network server starts. ```APIDOC ## network.StartHandler ### Description Handler called when server starts. ### Signature ```go type StartHandler func() ``` ``` -------------------------------- ### Consul Service Registration and Discovery Example Source: https://github.com/dobyte/due/blob/main/registry/consul/README-ZH.md Demonstrates how to register, update, watch, and deregister a service instance using the Consul registry in a Go application. ```go package main import ( "context" "github.com/dobyte/due/registry/consul/v2" "github.com/dobyte/due/v2/cluster" "github.com/dobyte/due/v2/log" "github.com/dobyte/due/v2/registry" "github.com/dobyte/due/v2/utils/xuuid" "time" ) func main() { var ( reg = consul.NewRegistry() id, _ = xuuid.UUID() name = "game-server" alias = "mahjong" ins = ®istry.ServiceInstance{ ID: id, Name: name, Kind: cluster.Node.String(), Alias: alias, State: cluster.Work.String(), Endpoint: "grpc://127.0.0.1:6339", } ) // 监听 watch(reg, name, 1) watch(reg, name, 2) // 注册服务 ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second) err := reg.Register(ctx, ins) cancel() if err != nil { log.Fatal(err) } time.Sleep(2 * time.Second) // 更新服务 ins.State = cluster.Busy.String() ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second) err = reg.Register(ctx, ins) cancel() if err != nil { log.Fatal(err) } time.Sleep(5 * time.Second) // 解注册服务 ctx, cancel = context.WithTimeout(context.Background(), 2*time.Second) err = reg.Deregister(ctx, ins) cancel() if err != nil { log.Fatal(err) } time.Sleep(10 * time.Second) } func watch(reg *consul.Registry, serviceName string, goroutineID int) { ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) watcher, err := reg.Watch(ctx, serviceName) cancel() if err != nil { log.Fatal(err) } go func() { for { services, err := watcher.Next() if err != nil { log.Fatalf("goroutine %d: %v", goroutineID, err) return } log.Infof("goroutine %d: new event entity", goroutineID) for _, service := range services { log.Infof("goroutine %d: %+v", goroutineID, service) } } }() } ``` -------------------------------- ### Perform File Existence Checks and Get Current Directory Source: https://github.com/dobyte/due/blob/main/_autodocs/utilities.md Use the xos package to check if a file exists and to get the current working directory. ```Go import "github.com/dobyte/due/v2/utils/xos" // File operations exists := xos.FileExists("./config.yaml") dir := xos.GetCurrentDir() absolute := xos.AbsPath("./config.yaml") ``` -------------------------------- ### Create and Start KCP Server Source: https://github.com/dobyte/due/blob/main/_autodocs/network-and-protocols.md Initializes a KCP server with a specified address and maximum connection count. Similar to TCP, it supports handlers for connection lifecycle events. ```go import "github.com/dobyte/due/v2/network/kcp" server := kcp.NewServer( kcp.WithAddr(":4000"), kcp.WithMaxConnNum(5000), ) // Same handlers as TCP server.OnConnect(func(conn network.Conn) {}) server.OnReceive(func(conn network.Conn, data []byte) {}) server.OnDisconnect(func(conn network.Conn) {}) server.Start() ``` -------------------------------- ### Etcd Configuration Options Source: https://github.com/dobyte/due/blob/main/config/etcd/README-ZH.md Example TOML configuration for the Etcd configuration center, specifying connection addresses, timeouts, path, and read/write mode. ```toml # 配置中心 [config] # etcd配置中心 [config.etcd] # 客户端连接地址,默认为["127.0.0.1:2379"] addrs = ["127.0.0.1:2379"] # 客户端拨号超时时间,支持单位:纳秒(ns)、微秒(us | µs)、毫秒(ms)、秒(s)、分(m)、小时(h)、天(d)。默认为5s dialTimeout = "5s" # 路径。默认为/config path = "/config" # 读写模式。可选:read-only | write-only | read-write,默认为read-only mode = "read-write" ``` -------------------------------- ### Cluster Component Lifecycle Hooks Source: https://github.com/dobyte/due/blob/main/_autodocs/types.md Defines integer constants for component lifecycle hooks: Init, Start, Close, and Destroy. ```go const ( Init Hook = iota // Component initialization Start // Component start Close // Component close Destroy // Component destruction ) ``` -------------------------------- ### Consul Configuration Options Source: https://github.com/dobyte/due/blob/main/config/consul/README-ZH.md Example TOML configuration for the Consul configuration center, specifying the client address, path, and read/write mode. ```toml # 配置中心 [config] # consul配置中心 [config.consul] # 客户端连接地址 addr = "127.0.0.1:8500" # 路径。默认为config path = "config" # 读写模式。可选:read-only | write-only | read-write,默认为read-only mode = "read-write" ``` -------------------------------- ### Initialize Consul Registry Source: https://github.com/dobyte/due/blob/main/_autodocs/INDEX.md Example of how to initialize the Consul registry client. Specify the addresses of the Consul servers using the WithAddrs option. Ensure the consul package is imported. ```go import "github.com/dobyte/due/v2/registry/consul" registry := consul.NewRegistry( consul.WithAddrs("localhost:8500"), ) ``` -------------------------------- ### component.Component Source: https://github.com/dobyte/due/blob/main/_autodocs/types.md Base interface for framework components, defining methods for name, initialization, starting, closing, and destruction. ```APIDOC ## component.Component ### Description Base interface for framework components. ### Methods ```go type Component interface { Name() string Init() Start() Close() Destroy() } ``` ``` -------------------------------- ### Create and Start TCP Server Source: https://github.com/dobyte/due/blob/main/_autodocs/network-and-protocols.md Creates a new TCP server listening on a specified address with a maximum connection limit. It also defines handlers for connection events like connect, receive, and disconnect. ```go import "github.com/dobyte/due/v2/network/tcp" server := tcp.NewServer( tcp.WithAddr(":3000"), tcp.WithMaxConnNum(5000), ) server.OnConnect(func(conn network.Conn) { log.Infof("TCP client connected: %s", conn.RemoteIP()) }) server.OnReceive(func(conn network.Conn, data []byte) { // Process received data }) server.OnDisconnect(func(conn network.Conn) { log.Infof("TCP client disconnected") }) server.Start() ``` -------------------------------- ### Multiple Node Instances for HA Source: https://github.com/dobyte/due/blob/main/_autodocs/cluster-architecture.md Shows a high availability setup with multiple Node instances that are dynamically discoverable and manageable via the registry. ```text Gate -> Registry -> [Node-1, Node-2, Node-3] | +-> Dispatch strategy selects Node +-> Can add/remove Nodes dynamically ``` -------------------------------- ### Get Type Information with Reflection Source: https://github.com/dobyte/due/blob/main/_autodocs/utilities.md Use the xreflect package to retrieve the type name and kind of a value dynamically. ```Go import "github.com/dobyte/due/v2/utils/xreflect" // Type information typeName := xreflect.TypeName(value) kind := xreflect.Kind(value) ``` -------------------------------- ### Component State Check and Hook Source: https://github.com/dobyte/due/blob/main/_autodocs/cluster-architecture.md Provides Go code examples for checking the current state of a component (e.g., Gate) and registering a hook for state change events. ```go // Check component state state := gate.State() // Shut, Work, Busy, Hang // Register state change hook gate.OnStateChange(func(newState cluster.State) { log.Infof("Gate state changed to: %v", newState) }) ``` -------------------------------- ### EventBus Package Source: https://github.com/dobyte/due/blob/main/_autodocs/api-reference.md Provides a publish-subscribe event system supporting multiple backends, with functions to set, get, publish, subscribe, and unsubscribe. ```APIDOC ## EventBus Package ### Eventbus Interface Publish-subscribe event system supporting multiple backends. **Package:** `github.com/dobyte/due/v2/eventbus` ```go type Eventbus interface { Close() error Publish(ctx context.Context, topic string, message any) error Subscribe(ctx context.Context, topic string, handler EventHandler) error Unsubscribe(ctx context.Context, topic string, handler EventHandler) error } ``` #### SetEventbus(eb Eventbus) Sets the global eventbus instance. ```go func SetEventbus(eb Eventbus) ``` #### GetEventbus() Eventbus Returns the current global eventbus. ```go func GetEventbus() Eventbus ``` #### Publish(ctx context.Context, topic string, message any) error Publishes a message to a topic. ```go func Publish(ctx context.Context, topic string, message any) error ``` #### Subscribe(ctx context.Context, topic string, handler EventHandler) error Subscribes to a topic with an event handler. ```go func Subscribe(ctx context.Context, topic string, handler EventHandler) error ``` **Parameters:** | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | ctx | `context.Context` | Yes | Context for the operation | | topic | `string` | Yes | Topic name | | handler | `EventHandler` | Yes | Handler function to call on events | ``` -------------------------------- ### Mesh Service Definition and Registration Source: https://github.com/dobyte/due/blob/main/_autodocs/cluster-architecture.md Define an RPC service (e.g., gRPC) for a mesh component and register it with the mesh. The example shows a Login service implementation. ```go // Example gRPC service type AuthService struct { pb.UnimplementedAuthServiceServer } func (s *AuthService) Login(ctx context.Context, req *pb.LoginRequest) (*pb.LoginResponse, error) { // Authenticate user return &pb.LoginResponse{Token: token}, nil } // Register with mesh mesh.RegisterService(&pb.AuthService{ // Implementation }) ``` -------------------------------- ### Log Package Source: https://github.com/dobyte/due/blob/main/_autodocs/api-reference.md Provides a framework logging interface with multiple log levels and functions to set, get, and use the global logger. ```APIDOC ## Log Package ### Logger Interface Framework logging interface with multiple log levels. **Package:** `github.com/dobyte/due/v2/log` ```go type Logger interface { Debug(a ...any) Debugf(format string, a ...any) Info(a ...any) Infof(format string, a ...any) Warn(a ...any) Warnf(format string, a ...any) Error(a ...any) Errorf(format string, a ...any) Fatal(a ...any) Fatalf(format string, a ...any) Panic(a ...any) Panicf(format string, a ...any) Print(level Level, a ...any) Printf(level Level, format string, a ...any) Close() error } ``` #### SetLogger(logger Logger) Sets the global logger instance. ```go func SetLogger(logger Logger) ``` #### GetLogger() Logger Returns the current global logger. ```go func GetLogger() Logger ``` #### Debug/Debugf(format string, a ...any) Logs debug-level messages. ```go func Debug(a ...any) func Debugf(format string, a ...any) ``` #### Info/Infof(format string, a ...any) Logs info-level messages. ```go func Info(a ...any) func Infof(format string, a ...any) ``` #### Warn/Warnf(format string, a ...any) Logs warning-level messages. ```go func Warn(a ...any) func Warnf(format string, a ...any) ``` #### Error/Errorf(format string, a ...any) Logs error-level messages. ```go func Error(a ...any) func Errorf(format string, a ...any) ``` #### Fatal/Fatalf(format string, a ...any) Logs fatal error and exits. ```go func Fatal(a ...any) func Fatalf(format string, a ...any) ``` #### Panic/Panicf(format string, a ...any) Logs panic and recovers. ```go func Panic(a ...any) func Panicf(format string, a ...any) ``` #### Close() Closes the logger. ```go func Close() ``` ``` -------------------------------- ### Task Package Source: https://github.com/dobyte/due/blob/main/_autodocs/api-reference.md Provides a goroutine pool for managing concurrent tasks, with functions to set, get, add, and release the global task pool. ```APIDOC ## Task Package ### Pool Interface Goroutine pool for managing concurrent tasks. **Package:** `github.com/dobyte/due/v2/task` ```go type Pool interface { AddTask(task func()) error Release() } ``` #### SetPool(pool Pool) Sets the global task pool. ```go func SetPool(pool Pool) ``` #### GetPool() Pool Returns the current global task pool. ```go func GetPool() Pool ``` #### AddTask(task func()) Adds a task to the global pool. Falls back to goroutine if pool is full. ```go func AddTask(task func()) ``` #### Release() Releases the task pool and cleans up resources. ```go func Release() ``` ``` -------------------------------- ### Inspect and Copy Struct Fields with Reflection Source: https://github.com/dobyte/due/blob/main/_autodocs/utilities.md The xreflect package allows you to get a list of fields for a struct and perform deep copies of values. ```Go import "github.com/dobyte/due/v2/utils/xreflect" // Field operations fields := xreflect.Fields(struct_value) field := xreflect.Field(struct_value, "fieldName") // Deep copy copy := xreflect.DeepCopy(original) ``` -------------------------------- ### Server Handler Types Source: https://github.com/dobyte/due/blob/main/_autodocs/network-and-protocols.md Defines the function signatures for various event handlers used by the network server, including start, stop, connect, disconnect, and receive events. ```go type ( StartHandler func() CloseHandler func() ConnectHandler func(conn Conn) DisconnectHandler func(conn Conn) ReceiveHandler func(conn Conn, data []byte) ) ``` -------------------------------- ### Initialize and Use File Configuration Source: https://github.com/dobyte/due/blob/main/config/file/README-ZH.md Initialize the file configuration source and demonstrate storing and retrieving configuration values. ```go package main import ( "context" "github.com/dobyte/due/v2/config" "github.com/dobyte/due/v2/config/file" "github.com/dobyte/due/v2/log" "time" ) func init() { // 设置全局配置器 config.SetConfigurator(config.NewConfigurator(config.WithSources(file.NewSource()))) } func main() { var ( ctx = context.Background() name = file.Name filepath = "config.toml" ) // 更新配置 if err := config.Store(ctx, name, filepath, map[string]any{ "timezone": "Local", }); err != nil { log.Errorf("store config failed: %v", err) return } time.Sleep(5 * time.Millisecond) // 读取配置 timezone := config.Get("config.timezone", "UTC").String() log.Infof("timezone: %s", timezone) // 更新配置 if err := config.Store(ctx, name, filepath, map[string]any{ "timezone": "UTC", }); err != nil { log.Errorf("store config failed: %v", err) return } time.Sleep(5 * time.Millisecond) // 读取配置 timezone = config.Get("config.timezone", "UTC").String() log.Infof("timezone: %s", timezone) } ``` -------------------------------- ### Get Current Time in Configured Timezone Source: https://github.com/dobyte/due/blob/main/_autodocs/utilities.md Use xtime.Now() to get the current time, which respects the configured timezone (etc.timezone). Always prefer this over time.Now() for timezone consistency. ```Go import "github.com/dobyte/due/v2/utils/xtime" now := xtime.Now() // Respects etc.timezone setting ``` -------------------------------- ### Common Server Options Configuration Source: https://github.com/dobyte/due/blob/main/_autodocs/network-and-protocols.md Illustrates how to configure common network server options such as listening address, maximum connections, buffer sizes, and TLS/SSL settings. ```go // Address to listen on server := tcp.NewServer(tcp.WithAddr(":3000")) // Maximum concurrent connections server := tcp.NewServer(tcp.WithMaxConnNum(10000)) // Read/Write buffer sizes server := tcp.NewServer(tcp.WithReadBufferSize(4096)) // TLS/SSL for secure connections server := tcp.NewServer(tcp.WithKeyFile("./certs/key.pem")) ``` -------------------------------- ### Build and Process Middleware Chain Source: https://github.com/dobyte/due/blob/main/_autodocs/utilities.md Demonstrates how to construct a middleware chain with multiple middleware functions and then process data through the chain. Ensure middleware functions are ordered correctly. ```Go import "github.com/dobyte/due/v2/core/chains" // Build middleware chain chain := chains.NewChain( loggingMiddleware, authMiddleware, rateLimitMiddleware, ) // Execute chain chain.Process(context.Background(), data) ``` -------------------------------- ### TCP Server Creation Source: https://github.com/dobyte/due/blob/main/_autodocs/network-and-protocols.md Demonstrates how to create and configure a TCP server, including setting up connection, receive, and disconnect handlers. ```APIDOC ## TCP Server Creation ### Description Creates a TCP server instance with specified options and registers handlers for connection events. ### Method `tcp.NewServer` ### Parameters - `tcp.Option` (variadic) - `tcp.WithAddr(addr string)`: Sets the server address. - `tcp.WithMaxConnNum(num int)`: Sets the maximum number of concurrent connections. ### Handlers - `OnConnect(handler func(conn network.Conn))`: Registers a handler for new client connections. - `OnReceive(handler func(conn network.Conn, data []byte))`: Registers a handler for receiving data from clients. - `OnDisconnect(handler func(conn network.Conn))`: Registers a handler for client disconnections. ### Start `server.Start()`: Starts the TCP server to listen for incoming connections. ### Request Example ```go import "github.com/dobyte/due/v2/network/tcp" server := tcp.NewServer( tcp.WithAddr(":3000"), tcp.WithMaxConnNum(5000), ) server.OnConnect(func(conn network.Conn) { log.Infof("TCP client connected: %s", conn.RemoteIP()) }) server.OnReceive(func(conn network.Conn, data []byte) { // Process received data }) server.OnDisconnect(func(conn network.Conn) { log.Infof("TCP client disconnected") }) server.Start() ``` ``` -------------------------------- ### Router Initialization and Usage Source: https://github.com/dobyte/due/blob/main/_autodocs/cluster-architecture.md Initialize a router and register routes, middleware, and event handlers. Middleware can be applied globally to the router. ```go router := node.Router() // Register routes router.AddRoute(10, handlerFunc) // Middleware support router.Use(authMiddleware, loggingMiddleware) // Event handlers router.OnMessageReceived(func(cid, uid int64, route int32, msg any) {}) ``` -------------------------------- ### KCP Server Creation Source: https://github.com/dobyte/due/blob/main/_autodocs/network-and-protocols.md Demonstrates how to create and configure a KCP server, similar to TCP but optimized for low-latency communication. ```APIDOC ## KCP Server Creation ### Description Creates a KCP server instance with specified options and registers handlers for connection events. ### Method `kcp.NewServer` ### Parameters - `kcp.Option` (variadic) - `kcp.WithAddr(addr string)`: Sets the server address. - `kcp.WithMaxConnNum(num int)`: Sets the maximum number of concurrent connections. ### Handlers - `OnConnect(handler func(conn network.Conn))`: Registers a handler for new client connections. - `OnReceive(handler func(conn network.Conn, data []byte))`: Registers a handler for receiving data from clients. - `OnDisconnect(handler func(conn network.Conn))`: Registers a handler for client disconnections. ### Start `server.Start()`: Starts the KCP server to listen for incoming connections. ### Request Example ```go import "github.com/dobyte/due/v2/network/kcp" server := kcp.NewServer( kcp.WithAddr(":4000"), kcp.WithMaxConnNum(5000), ) // Same handlers as TCP server.OnConnect(func(conn network.Conn) {}) server.OnReceive(func(conn network.Conn, data []byte) {}) server.OnDisconnect(func(conn network.Conn) {}) server.Start() ``` ``` -------------------------------- ### Initialize Node Component Source: https://github.com/dobyte/due/blob/main/_autodocs/cluster-architecture.md Initializes a new Node component with configurations for ID, name, registry, locator, and transporter. ```go import "github.com/dobyte/due/v2/cluster/node" node := node.NewNode( node.WithID("node-1"), node.WithName("node"), node.WithRegistry(registryService), node.WithLocator(locatorService), node.WithTransporter(transportService), ) ``` -------------------------------- ### Wait for Async Operation Results Source: https://github.com/dobyte/due/blob/main/_autodocs/utilities.md Call the Get method on the result of an xcall.Async operation to retrieve the computed value or error. ```Go import "github.com/dobyte/due/v2/utils/xcall" // Wait for result value, err := result.Get(context.Background()) ``` -------------------------------- ### Get Error Code Source: https://github.com/dobyte/due/blob/main/_autodocs/errors.md Retrieve the error code from an error if it's available. Returns nil if the error does not have an associated code. ```go func Code(err error) *codes.Code ``` ```go if code := errors.Code(err); code != nil { log.Infof("Error code: %s", code) } ``` -------------------------------- ### TCP Client Creation Source: https://github.com/dobyte/due/blob/main/_autodocs/network-and-protocols.md Demonstrates how to create a TCP client, establish a connection to a server, and handle incoming data. ```APIDOC ## TCP Client Creation ### Description Creates a TCP client, dials a server address, and sets up a handler for receiving data. ### Method `tcp.NewClient()` ### Dial `client.Dial(addr string)`: Establishes a connection to the specified server address. ### Handlers - `OnReceive(handler func(conn network.Conn, data []byte))`: Registers a handler for receiving data from the server. ### Send `conn.Send(data []byte)`: Sends data to the connected server. ### Request Example ```go import "github.com/dobyte/due/v2/network/tcp" client := tcp.NewClient() conn, err := client.Dial("localhost:3000") if err != nil { log.Errorf("Failed to connect: %v", err) return } client.OnReceive(func(conn network.Conn, data []byte) { // Handle received data }) conn.Send(data) ``` ``` -------------------------------- ### Watcher Interface Source: https://github.com/dobyte/due/blob/main/_autodocs/api-reference.md Interface for watching service instance changes. Provides methods to get the next set of changes and to stop watching. ```go type Watcher interface { Next() ([]*ServiceInstance, error) Stop() error } ``` -------------------------------- ### Connect to TCP Server Source: https://github.com/dobyte/due/blob/main/_autodocs/network-and-protocols.md Creates a TCP client and attempts to establish a connection to a specified server address. It also sets up a handler for receiving data from the server. ```go client := tcp.NewClient() conn, err := client.Dial("localhost:3000") if err != nil { log.Errorf("Failed to connect: %v", err) return } client.OnReceive(func(conn network.Conn, data []byte) { // Handle received data }) conn.Send(data) ``` -------------------------------- ### Logging Cluster Events Source: https://github.com/dobyte/due/blob/main/_autodocs/cluster-architecture.md Demonstrates how to use the Dobyte Due framework logger for various cluster events, including startup, warnings, and errors. Ensure the log package is imported. ```go import "github.com/dobyte/due/v2/log" log.Infof("Gate started: %s", gate.Name()) log.Warnf("Connection limit exceeded") log.Errorf("Failed to register service: %v", err) ``` -------------------------------- ### Get Next Error in Chain Source: https://github.com/dobyte/due/blob/main/_autodocs/errors.md Retrieve the next error in a sequence of chained errors. Returns nil if there is no subsequent error in the chain. ```go func Next(err error) error ``` -------------------------------- ### Graceful Shutdown Implementation Source: https://github.com/dobyte/due/blob/main/_autodocs/cluster-architecture.md Demonstrates the implementation of graceful shutdown using `container.Serve()`, which automatically handles the shutdown sequence upon receiving termination signals. ```go container.Serve() // Waits for SIGINT/SIGTERM/SIGKILL // Automatically handles shutdown sequence ``` -------------------------------- ### Initialize Gate Component Source: https://github.com/dobyte/due/blob/main/_autodocs/cluster-architecture.md Initializes a new Gate component with essential configurations like ID, name, server, locator, and registry. ```go import "github.com/dobyte/due/v2/cluster/gate" gate := gate.NewGate( gate.WithID("gate-1"), gate.WithName("gate"), gate.WithServer(tcpServer), gate.WithLocator(locatorService), gate.WithRegistry(registryService), ) ``` -------------------------------- ### Troubleshoot Connection Refused Source: https://github.com/dobyte/due/blob/main/_autodocs/network-and-protocols.md Verify server listening address and check firewall rules. Use telnet for basic connectivity testing. ```go // Check listening address log.Infof("Server listening on: %s", server.Addr()) // Verify firewall allows traffic // Test with: telnet localhost 3000 ``` -------------------------------- ### Get Error Code Source: https://github.com/dobyte/due/blob/main/_autodocs/INDEX.md This snippet demonstrates how to extract an error code from an error object. This is useful for handling errors based on their type or category. ```go code := errors.Code(err) ``` -------------------------------- ### WebSocket Server Creation Source: https://github.com/dobyte/due/blob/main/_autodocs/network-and-protocols.md Demonstrates how to create and configure a WebSocket server for web client connections. ```APIDOC ## WebSocket Server Creation ### Description Creates a WebSocket server instance with specified options and registers handlers for connection events. ### Method `ws.NewServer` ### Parameters - `ws.Option` (variadic) - `ws.WithAddr(addr string)`: Sets the server address. - `ws.WithPath(path string)`: Sets the WebSocket path. ### Handlers - `OnConnect(handler func(conn network.Conn))`: Registers a handler for new client connections. - `OnReceive(handler func(conn network.Conn, data []byte))`: Registers a handler for receiving data from clients. - `OnDisconnect(handler func(conn network.Conn))`: Registers a handler for client disconnections. ### Start `server.Start()`: Starts the WebSocket server to listen for incoming connections. ### Request Example ```go import "github.com/dobyte/due/v2/network/ws" server := ws.NewServer( ws.WithAddr(":8000"), ws.WithPath("/game"), ) server.OnConnect(func(conn network.Conn) {}) server.OnReceive(func(conn network.Conn, data []byte) {}) server.OnDisconnect(func(conn network.Conn) {}) server.Start() ``` ``` -------------------------------- ### Enable Swagger/OpenAPI Documentation Source: https://github.com/dobyte/due/blob/main/_autodocs/configuration.md Configure Swagger/OpenAPI documentation. Set the title, base path, and file path for the documentation. ```toml [http.swagger] enable = true title = "My API" basePath = "/swagger" filePath = "./docs/swagger.json" swaggerBundleUrl = "" swaggerPresetUrl = "" swaggerStylesUrl = "" ``` -------------------------------- ### Lock Package Source: https://github.com/dobyte/due/blob/main/_autodocs/api-reference.md Provides a distributed lock factory and interface for acquiring and releasing locks, with functions to set, get, make, and close the lock maker. ```APIDOC ## Lock Package ### Maker Interface Distributed lock factory for creating named locks. **Package:** `github.com/dobyte/due/v2/lock` ```go type Maker interface { Make(name string) Locker Close() error } ``` ### Locker Interface Distributed lock interface for acquiring and releasing locks. ```go type Locker interface { Acquire(ctx context.Context) error TryAcquire(ctx context.Context, expiration ...time.Duration) error Release(ctx context.Context) error } ``` #### SetMaker(maker Maker) Sets the global lock maker. ```go func SetMaker(maker Maker) ``` #### GetMaker() Maker Returns the current global lock maker. ```go func GetMaker() Maker ``` #### Make(name string) Locker Creates a named locker instance. ```go func Make(name string) Locker ``` #### Close() error Closes the lock maker. ```go func Close() error ``` **Example:** ```go locker := lock.Make("resource-lock") if err := locker.Acquire(ctx); err != nil { // Handle error return } defer locker.Release(ctx) // Critical section ``` ``` -------------------------------- ### Get Root Cause of Error Source: https://github.com/dobyte/due/blob/main/_autodocs/errors.md Retrieve the root cause from a chain of errors. This function helps in unwrapping nested errors to find the original error. ```go func Cause(err error) error ``` ```go rootErr := errors.Cause(err) ``` -------------------------------- ### Buffer Management with Pool Source: https://github.com/dobyte/due/blob/main/_autodocs/utilities.md Shows how to obtain a buffer from the pool, perform write operations, and release the buffer back to the pool when done. Remember to release buffers to avoid memory leaks. ```Go import "github.com/dobyte/due/v2/core/buffer" // Get buffer from pool buf := buffer.NewBuffer() def buf.Release() // Return to pool // Write operations buf.Write([]byte("hello")) buf.WriteString("world") // Read operations data := buf.Bytes() ``` -------------------------------- ### Collect and Retrieve Statistics Source: https://github.com/dobyte/due/blob/main/_autodocs/utilities.md Demonstrates how to create a statistics collector and record various metrics like requests, errors, and latency. Use this for performance monitoring. ```Go import "github.com/dobyte/due/v2/core/stat" // Create statistics stat := core/stat.NewStat() // Record operations stat.RecordRequest() stat.RecordError() stat.RecordLatency(duration) // Get metrics count := stat.RequestCount() errors := stat.ErrorCount() latency := stat.AverageLatency() ``` -------------------------------- ### Logging Messages Source: https://github.com/dobyte/due/blob/main/_autodocs/INDEX.md Demonstrates how to use the Due logging package to output messages at different severity levels (Debug, Info, Warning, Error). Ensure the log package is imported. ```go import "github.com/dobyte/due/v2/log" log.Debugf("Debug message") log.Infof("Info message") log.Warnf("Warning message") log.Errorf("Error: %v", err) ``` -------------------------------- ### Create and Inspect Errors Source: https://github.com/dobyte/due/blob/main/_autodocs/utilities.md Demonstrates how to create new errors with optional causes or error codes and how to retrieve error information like cause, code, and next error. ```Go import "github.com/dobyte/due/v2/errors" // Create error err := errors.NewError("operation failed") err := errors.NewError("operation failed", someError) err := errors.NewError("operation failed", someErrorCode) // Retrieve error information cause := errors.Cause(err) code := errors.Code(err) next := errors.Next(err) ``` -------------------------------- ### Round-Robin Load Balancing Source: https://github.com/dobyte/due/blob/main/_autodocs/cluster-architecture.md Demonstrates the round-robin load balancing strategy, cycling through available instances sequentially. ```text Request 1 -> Node-1 Request 2 -> Node-2 Request 3 -> Node-3 Request 4 -> Node-1 (cycle) ``` -------------------------------- ### HTTP SSL/TLS Key File Configuration Source: https://github.com/dobyte/due/blob/main/_autodocs/configuration.md Path to the private key file for enabling HTTPS. ```toml keyFile = "./certs/server.key" ``` -------------------------------- ### File Configuration Settings Source: https://github.com/dobyte/due/blob/main/config/file/README-ZH.md Configure the path and read-write mode for the file configuration source. ```toml # 配置中心 [config] # 文件配置 [config.file] # 配置文件或配置目录路径 path = "./config" # 读写模式。可选:read-only | write-only | read-write,默认为read-only mode = "read-write" ``` -------------------------------- ### Retrieve Configuration Values as value.Value Source: https://github.com/dobyte/due/blob/main/_autodocs/utilities.md Use the config.Get function to retrieve configuration values, which are returned as value.Value for easy conversion. ```Go import ( "github.com/dobyte/due/v2/config" "github.com/dobyte/due/v2/etc" ) // Configuration retrieval v := config.Get("cluster.gate.id") id := v.String() v := config.Get("cluster.node.weight") weight := v.Int() v := config.Get("cluster.node.metadata") metadata := v.Map() ``` -------------------------------- ### ServiceInstance Struct Source: https://github.com/dobyte/due/blob/main/_autodocs/api-reference.md Represents a service instance with its metadata, state, and configuration. Used for registration and discovery. ```go type ServiceInstance struct { ID string // Unique service instance ID Name string // Service name Kind string // Service kind/type Alias string // Service alias State string // Service state Events []int // Event IDs Routes []Route // Route definitions Services []string // Service names Endpoint string // Service endpoint address Weight int // Weight for load balancing Metadata map[string]string // Custom metadata } ``` -------------------------------- ### Read and Write Files with xos Source: https://github.com/dobyte/due/blob/main/_autodocs/utilities.md The xos package simplifies reading file content into a byte slice and writing byte slices to files. ```Go import "github.com/dobyte/due/v2/utils/xos" // File I/O content, _ := xos.ReadFile("./config.yaml") _ = xos.WriteFile("./output.txt", []byte("content")) ``` -------------------------------- ### Mesh Initialization Source: https://github.com/dobyte/due/blob/main/_autodocs/cluster-architecture.md Initialize a mesh component with essential configurations like ID, name, registry, and transporter services. This is used for stateless microservices. ```go import "github.com/dobyte/due/v2/cluster/mesh" mesh := mesh.NewMesh( mesh.WithID("auth-mesh-1"), mesh.WithName("auth"), mesh.WithRegistry(registryService), mesh.WithTransporter(transportService), ) ``` -------------------------------- ### HTTP SSL/TLS Certificate File Configuration Source: https://github.com/dobyte/due/blob/main/_autodocs/configuration.md Path to the certificate file for enabling HTTPS. ```toml certFile = "./certs/server.crt" ``` -------------------------------- ### Register Route with Options Source: https://github.com/dobyte/due/blob/main/_autodocs/cluster-architecture.md Register a route with additional options like statefulness and authorization requirements. Stateful routes require actor affinity. ```go // Provide metadata about route node.Router().AddRoute(101, node.WithRouteHandler(func(ctx *node.Context) {}), node.WithStateful(true), // Requires actor affinity node.WithAuthorized(true), // Requires authentication ) ``` -------------------------------- ### Token Bucket Rate Limiter Source: https://github.com/dobyte/due/blob/main/_autodocs/utilities.md Shows how to create and use a token bucket rate limiter. This is useful for controlling the rate of operations to prevent abuse or overload. Call Allow() to check if an operation is permitted. ```Go import "github.com/dobyte/due/v2/core/limiter" // Token bucket limiter limiter := core/limiter.NewTokenBucketLimiter( 100, // Max tokens time.Second, // Refill interval ) // Check if allowed if limiter.Allow() { // Proceed } ```