package nacos import ( "errors" "net" "os" "strconv" "strings" "sync" "github.com/nacos-group/nacos-sdk-go/v2/common/constant" ) var ( cc *constant.ClientConfig sc []constant.ServerConfig initMu sync.Once ) func GetIP(domain string) string { if domain == "" { return "" } ips, err := net.LookupIP(domain) if err != nil || len(ips) == 0 { return "" } for _, ip := range ips { if ipv4 := ip.To4(); ipv4 != nil { return ipv4.String() } } return ips[0].String() } func InitNacosRegistryConfig() error { var initErr error initMu.Do(func() { hostsStr := os.Getenv("NACOS_HOSTS") portStr := os.Getenv("NACOS_PORT") if hostsStr == "" || portStr == "" { initErr = errors.New("NACOS_HOSTS 和 NACOS_PORT 必须配置") return } nacosPort, err := strconv.Atoi(portStr) if err != nil { initErr = errors.New("NACOS_PORT 格式错误") return } nacosHosts := strings.Split(hostsStr, ",") for _, host := range nacosHosts { host = strings.TrimSpace(host) if host == "" { continue } ip := GetIP(host) if ip == "" { ip = host } serverConfig := constant.NewServerConfig(ip, uint64(nacosPort)) sc = append(sc, *serverConfig) } if len(sc) == 0 { initErr = errors.New("无有效的 Nacos 服务器地址") return } logDir := os.Getenv("LOG_SAVE_PATH") if logDir == "" { logDir = "/tmp/nacos/log" } cc = &constant.ClientConfig{ NamespaceId: os.Getenv("NACOS_NAMESPACE"), TimeoutMs: 5000, NotLoadCacheAtStart: true, LogDir: logDir, LogLevel: "warn", Username: os.Getenv("NACOS_USER"), Password: os.Getenv("NACOS_PASSWORD"), } }) return initErr }