新增 zhub 客户端完整实现,包括配置加载、TCP通信、消息发布/订阅、 RPC 调用、分布式锁等功能。支持从项目配置文件、环境变量等多种方式初始化客户端,并提供便捷的全局调用接口。- 添加 `.gitignore` 忽略 IDE 和临时文件 - 实现 `api.go` 提供全局便捷方法封装客户端调用 - 实现 `client.go` 核心客户端逻辑,包含网络通信、消息处理等 - 添加 `client_test.go` 单元测试和集成测试示例 - 实现 `config.go` 支持灵活的配置加载机制 - 添加示例配置文件 `example-config.yml` - 初始化 Go 模块依赖 `go.mod` 和 `go.sum` - 实现 `init.go` 提供多种初始化方式 - 添加 MIT 许可证文件 `LICENSE` - 新增使用示例 `example/main.go` 展示基本功能调用 - 实现 `manager.go` 管理默认客户端实例及初始化逻辑
98 lines
2.4 KiB
Go
98 lines
2.4 KiB
Go
package zhub
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
|
|
"github.com/spf13/viper"
|
|
)
|
|
|
|
// Config zhub客户端配置
|
|
type Config struct {
|
|
Appname string `mapstructure:"appname"`
|
|
Addr string `mapstructure:"addr"`
|
|
Groupid string `mapstructure:"groupid"`
|
|
Auth string `mapstructure:"auth"`
|
|
}
|
|
|
|
// ConfigOptions 配置加载选项
|
|
type ConfigOptions struct {
|
|
ConfigPath string // 配置文件路径
|
|
ConfigName string // 配置文件名 (默认: "app")
|
|
ConfigType string // 配置文件类型 (默认: "yml")
|
|
ConfigKey string // 配置节点名 (默认: "zhub")
|
|
EnvPrefix string // 环境变量前缀 (可选)
|
|
}
|
|
|
|
// LoadConfigWithOptions 使用选项加载配置
|
|
func LoadConfigWithOptions(opts *ConfigOptions) (*Config, error) {
|
|
viper.Reset()
|
|
|
|
// 设置默认值
|
|
if opts.ConfigName == "" {
|
|
opts.ConfigName = "app"
|
|
}
|
|
if opts.ConfigType == "" {
|
|
opts.ConfigType = "yml"
|
|
}
|
|
if opts.ConfigKey == "" {
|
|
opts.ConfigKey = "zhub"
|
|
}
|
|
|
|
// 如果指定了配置文件路径,使用指定路径
|
|
if opts.ConfigPath != "" {
|
|
viper.SetConfigFile(opts.ConfigPath)
|
|
} else {
|
|
// 否则使用默认搜索路径
|
|
viper.SetConfigName(opts.ConfigName)
|
|
viper.SetConfigType(opts.ConfigType)
|
|
|
|
// 添加多个搜索路径
|
|
viper.AddConfigPath(".")
|
|
viper.AddConfigPath("./conf")
|
|
viper.AddConfigPath("./config")
|
|
viper.AddConfigPath("/etc")
|
|
}
|
|
|
|
// 设置环境变量前缀
|
|
if opts.EnvPrefix != "" {
|
|
viper.SetEnvPrefix(opts.EnvPrefix)
|
|
viper.AutomaticEnv()
|
|
}
|
|
|
|
// 读取配置文件
|
|
if err := viper.ReadInConfig(); err != nil {
|
|
return nil, fmt.Errorf("failed to read config file: %w", err)
|
|
}
|
|
|
|
var config Config
|
|
if err := viper.UnmarshalKey(opts.ConfigKey, &config); err != nil {
|
|
return nil, fmt.Errorf("failed to unmarshal config: %w", err)
|
|
}
|
|
|
|
return &config, nil
|
|
}
|
|
|
|
// LoadConfig 默认配置加载(向后兼容)
|
|
func LoadConfig(configPath string) (*Config, error) {
|
|
opts := &ConfigOptions{
|
|
ConfigPath: configPath,
|
|
ConfigKey: "zhub",
|
|
}
|
|
return LoadConfigWithOptions(opts)
|
|
}
|
|
|
|
// LoadConfigFromProject 从项目配置文件加载(推荐方式)
|
|
func LoadConfigFromProject(projectConfigPath string) (*Config, error) {
|
|
// 检查文件是否存在
|
|
if _, err := os.Stat(projectConfigPath); os.IsNotExist(err) {
|
|
return nil, fmt.Errorf("config file not found: %s", projectConfigPath)
|
|
}
|
|
|
|
opts := &ConfigOptions{
|
|
ConfigPath: projectConfigPath,
|
|
ConfigKey: "zhub",
|
|
}
|
|
return LoadConfigWithOptions(opts)
|
|
}
|