feat: 添加微服务模板基础架构

- 创建基于 CloudWego Hertz 的 Go 微服务脚手架
- 集成 Nacos 服务注册/发现功能
- 添加 gRPC 客户端支持
- 实现环境变量配置管理 (.env.example)
- 添加 HTTP 中间件 (Recovery, AccessLog, CORS)
- 配置 Gitea CI/CD 构建部署流程

BREAKING CHANGE: 项目结构调整,从简单的 API 服务升级为完整的微服务架构
This commit is contained in:
shiran
2026-04-15 11:13:38 +08:00
parent 8654cd6e5c
commit 6050d11f27
30 changed files with 1643 additions and 358 deletions
+58 -37
View File
@@ -1,66 +1,87 @@
package nacos
import (
"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
"errors"
"net"
"os"
"strconv"
"strings"
"sync"
"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
)
var (
cc *constant.ClientConfig
sc []constant.ServerConfig
cc *constant.ClientConfig
sc []constant.ServerConfig
initMu sync.Once
)
func GetIP(domain string) string {
// 确保域名不为空
if domain == "" {
return ""
}
// 使用 net.LookupIP 查找域名的 IP 地址
ips, err := net.LookupIP(domain)
if err != nil {
if err != nil || len(ips) == 0 {
return ""
}
// 检查是否找到了 IP
if len(ips) == 0 {
return ""
}
// 返回第一个 IPv4 地址(如果有)
for _, ip := range ips {
if ipv4 := ip.To4(); ipv4 != nil {
return ipv4.String()
}
}
// 如果没有 IPv4,返回第一个 IP(可能是 IPv6)
return ips[0].String()
}
func InitNacosRegistryConfig() {
if cc != nil && sc != nil {
return
}
nacosHosts := strings.Split(os.Getenv("NACOS_HOSTS"), ",")
nacosPort, _ := strconv.Atoi(os.Getenv("NACOS_PORT"))
for _, host := range nacosHosts {
serverConfig := constant.NewServerConfig(GetIP(host), uint64(nacosPort))
sc = append(sc, *serverConfig)
}
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
}
LogDir := os.Getenv("LOG_SAVE_PATH")
cc = &constant.ClientConfig{
NamespaceId: os.Getenv("NACOS_NAMESPACE"),
TimeoutMs: 5000,
NotLoadCacheAtStart: true,
LogDir: LogDir,
//CacheDir: "/tmp/nacos/cache",
LogLevel: "debug",
Username: os.Getenv("NACOS_USER"),
Password: os.Getenv("NACOS_PASSWORD"),
}
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
}