package utils import ( "encoding/json" "go-study/zinx/ziface" "os" "path/filepath" "runtime" ) // Config 存储 zinx 框架的全局配置 type Config struct { // TcpServer 服务器全局对象 TcpServer ziface.IServer // Host 服务器主机地址 Host string // TcpPort 服务器端口 TcpPort int // Name 服务器名称 Name string // Version 服务器版本号 Version string // MaxPacketSize 消息的最大包长度 MaxPacketSize uint32 // MaxConn 最大连接数 MaxConn int // WorkerPoolSize 业务工作 Worker 池的数量 WorkerPoolSize uint32 // MaxWorkerTaskLen 每个 Worker 对应负责的任务队列最大任务存储数量 MaxWorkerTaskLen uint32 // MaxMsgChanLen 缓冲消息队列最大长度 MaxMsgChanLen uint32 } // ConfigInstance 定义一个全局的配置实例 var ConfigInstance *Config func (c *Config) Reload() { // 基于当前源文件目录定位到项目下的 zinx/conf/zinx.json _, file, _, ok := runtime.Caller(0) if !ok { panic("cannot locate current file path") } configPath := filepath.Join(filepath.Dir(file), "..", "conf", "zinx.json") data, err := os.ReadFile(configPath) if err != nil { panic(err) } // 将 json 文件数据解析到 ConfigInstance 中 err = json.Unmarshal(data, &ConfigInstance) if err != nil { panic(err) } } func init() { // 初始化全局配置,并设置默认值 ConfigInstance = &Config{ Name: "ZinxServerApp", Version: "V0.9", Host: "0.0.0.0", TcpPort: 7777, MaxConn: 12000, MaxPacketSize: 4096, WorkerPoolSize: 10, MaxWorkerTaskLen: 1024, MaxMsgChanLen: 1024, } // 加载配置文件 ConfigInstance.Reload() }