56 lines
1.1 KiB
Go
56 lines
1.1 KiB
Go
package docker
|
|
|
|
import (
|
|
"sync"
|
|
|
|
"github.com/docker/docker/client"
|
|
|
|
"gitee.ltd/lxh/wechat-robot/internal/config"
|
|
)
|
|
|
|
var (
|
|
dockerClient *client.Client
|
|
clientOnce sync.Once
|
|
clientErr error
|
|
)
|
|
|
|
// InitClient 初始化Docker客户端
|
|
func InitClient(cfg *config.DockerConfig) error {
|
|
clientOnce.Do(func() {
|
|
options := []client.Opt{
|
|
client.WithAPIVersionNegotiation(),
|
|
}
|
|
|
|
// 如果指定了Docker主机地址
|
|
if cfg.Host != "" {
|
|
options = append(options, client.WithHost(cfg.Host))
|
|
}
|
|
|
|
// 如果指定了API版本
|
|
if cfg.APIVersion != "" {
|
|
options = append(options, client.WithVersion(cfg.APIVersion))
|
|
}
|
|
|
|
// 创建Docker客户端
|
|
dockerClient, clientErr = client.NewClientWithOpts(options...)
|
|
})
|
|
|
|
return clientErr
|
|
}
|
|
|
|
// GetClient 获取Docker客户端实例
|
|
func GetClient() *client.Client {
|
|
if dockerClient == nil {
|
|
panic("Docker client not initialized, call InitClient first")
|
|
}
|
|
return dockerClient
|
|
}
|
|
|
|
// CloseClient 关闭Docker客户端
|
|
func CloseClient() error {
|
|
if dockerClient != nil {
|
|
return dockerClient.Close()
|
|
}
|
|
return nil
|
|
}
|