初始化 zhub Go 客户端项目
新增 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` 管理默认客户端实例及初始化逻辑
This commit is contained in:
93
client_test.go
Normal file
93
client_test.go
Normal file
@@ -0,0 +1,93 @@
|
||||
package zhub
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestConfigLoading(t *testing.T) {
|
||||
// 测试配置加载
|
||||
opts := &ConfigOptions{
|
||||
ConfigPath: "example-config.yml",
|
||||
ConfigKey: "zhub",
|
||||
}
|
||||
|
||||
config, err := LoadConfigWithOptions(opts)
|
||||
if err != nil {
|
||||
t.Skipf("Config file not found, skipping test: %v", err)
|
||||
}
|
||||
|
||||
if config.Appname == "" {
|
||||
t.Error("Appname should not be empty")
|
||||
}
|
||||
|
||||
if config.Addr == "" {
|
||||
t.Error("Addr should not be empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestJSONConversion(t *testing.T) {
|
||||
// 测试 JSON 转换
|
||||
testCases := []struct {
|
||||
input interface{}
|
||||
expected string
|
||||
}{
|
||||
{"hello", "hello"},
|
||||
{123, "123"},
|
||||
{true, "true"},
|
||||
{map[string]interface{}{"key": "value"}, `{"key":"value"}`},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
result, err := ToJSON(tc.input)
|
||||
if err != nil {
|
||||
t.Errorf("ToJSON failed for %v: %v", tc.input, err)
|
||||
continue
|
||||
}
|
||||
|
||||
if result != tc.expected {
|
||||
t.Errorf("ToJSON(%v) = %s, expected %s", tc.input, result, tc.expected)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestClientCreation(t *testing.T) {
|
||||
// 注意:这个测试需要实际的 zhub 服务器运行
|
||||
t.Skip("Skipping integration test - requires zhub server")
|
||||
|
||||
config := &Config{
|
||||
Appname: "test-app",
|
||||
Addr: "127.0.0.1:1216",
|
||||
Groupid: "test-group",
|
||||
Auth: "test-token",
|
||||
}
|
||||
|
||||
client, err := NewClient(config)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create client: %v", err)
|
||||
}
|
||||
|
||||
defer client.Close()
|
||||
|
||||
// 测试发布消息
|
||||
err = client.Publish("test-topic", "test message")
|
||||
if err != nil {
|
||||
t.Errorf("Failed to publish message: %v", err)
|
||||
}
|
||||
|
||||
// 测试订阅
|
||||
messageReceived := make(chan string, 1)
|
||||
client.Subscribe("test-topic", func(message string) {
|
||||
messageReceived <- message
|
||||
})
|
||||
|
||||
// 等待消息
|
||||
select {
|
||||
case msg := <-messageReceived:
|
||||
if msg != "test message" {
|
||||
t.Errorf("Expected 'test message', got '%s'", msg)
|
||||
}
|
||||
case <-time.After(time.Second * 5):
|
||||
t.Error("Timeout waiting for message")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user