6050d11f27
- 创建基于 CloudWego Hertz 的 Go 微服务脚手架 - 集成 Nacos 服务注册/发现功能 - 添加 gRPC 客户端支持 - 实现环境变量配置管理 (.env.example) - 添加 HTTP 中间件 (Recovery, AccessLog, CORS) - 配置 Gitea CI/CD 构建部署流程 BREAKING CHANGE: 项目结构调整,从简单的 API 服务升级为完整的微服务架构
88 lines
1.7 KiB
Go
88 lines
1.7 KiB
Go
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
|
|
}
|