core/conf/new.go

123 lines
3.0 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Package conf 提供配置管理功能
// 支持YAML配置文件加载、环境变量替换、配置验证等
package conf
import (
"fmt"
"log"
"os"
"path/filepath"
"strings"
"time"
"math/rand/v2"
"git.apinb.com/bsm-sdk/core/env"
"git.apinb.com/bsm-sdk/core/printer"
"git.apinb.com/bsm-sdk/core/utils"
"git.apinb.com/bsm-sdk/core/vars"
yaml "gopkg.in/yaml.v3"
)
// New 加载配置文件
// srvKey: 服务键名
// cfg: 配置结构体指针
func New(srvKey string, cfg any) {
env.NewEnv()
// 设置服务键
vars.ServiceKey = srvKey
// 获取主机名
vars.HostName, _ = os.Hostname()
// 构造配置文件路径,输出配置文件信息
cfp := fmt.Sprintf("%s_%s.yaml", strings.ToLower(srvKey), env.Runtime.Mode)
cfp = filepath.Join(env.Runtime.Prefix, "etc", cfp)
// 配置文件不存在则读取Workspace配置文件
if !utils.PathExists(cfp) {
cfp = fmt.Sprintf("workspace_%s_%s.yaml", strings.ToLower(env.Runtime.Workspace), env.Runtime.Mode)
cfp = filepath.Join(env.Runtime.Prefix, "etc", cfp)
}
printer.Info("[BSM - %s] Config File: %s", srvKey, cfp)
printer.Info("[BSM - %s] Check Configure ...", vars.ServiceKey)
// 读取配置文件内容
yamlFile, err := os.ReadFile(cfp)
if err != nil {
log.Fatalf("ERROR: %v", err)
}
// 替换环境变量
yamlString := os.ExpandEnv(string(yamlFile))
// 检查配置文件中是否存在Service字段
if !strings.Contains(yamlString, "Service:") {
log.Fatalln("ERROR: Service Not Nil", cfp)
}
// 解析YAML到配置结构体
err = yaml.Unmarshal([]byte(yamlString), cfg)
if err != nil {
log.Fatalf("ERROR: %v", err)
}
}
// NotNil 验证必需配置项不为空
// values: 需要验证的配置值列表
func NotNil(values ...string) {
for _, value := range values {
if strings.TrimSpace(value) == "" {
log.Fatalln("ERROR:Must config key not nil")
}
}
}
// PrintInfo 打印配置信息
// addr: 服务地址
func PrintInfo(addr string) {
printer.Success("[BSM - %s] Config Check Success.", vars.ServiceKey)
printer.Info("[BSM - %s] Service Name: %s", vars.ServiceKey, vars.ServiceKey)
printer.Info("[BSM - %s] Runtime Mode: %s", vars.ServiceKey, env.Runtime.Mode)
}
// CheckPort 检查端口配置,如果为空则生成随机端口
// port: 端口字符串
// 返回: 有效的端口字符串
func CheckPort(port string) string {
if port == "" {
r := rand.New(rand.NewPCG(1000, uint64(time.Now().UnixNano())))
p := r.IntN(65535-1024) + 1024 // 生成1024到65535之间的随机端口
return utils.Int2String(p)
}
return port
}
// CheckIP 检查IP配置如果为空则获取本机IP
// ip: IP地址字符串
// 返回: 有效的IP地址字符串
func CheckIP(ip string) string {
if ip == "" {
return utils.GetLocationIP()
}
return ip
}
// 初始化Logger配置
func InitLoggerConf(cfg *LogConf) *LogConf {
if cfg == nil {
return &LogConf{
Name: strings.ToLower(vars.ServiceKey),
Level: vars.LogLevel(vars.DEBUG),
Dir: "./logs/",
Endpoint: "",
Console: true,
File: true,
Remote: false,
}
}
return cfg
}