71 lines
2.0 KiB
Go
71 lines
2.0 KiB
Go
// Package config ...
|
|
//
|
|
// Description : config ...
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 2024-11-05 16:23
|
|
package config
|
|
|
|
import (
|
|
"errors"
|
|
"git.zhangdeman.cn/zhangdeman/serialize"
|
|
"github.com/caarlos0/env/v9"
|
|
"github.com/jessevdk/go-flags"
|
|
"github.com/joho/godotenv"
|
|
"path/filepath"
|
|
)
|
|
|
|
// Init 初始化配置
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 16:25 2024/11/5
|
|
//
|
|
// 参数:
|
|
// - configReceiver 接收最终配置结果的指针
|
|
// - cliReceiver 命令函参数配置结果
|
|
// - envReceiver 环境变量配置结果
|
|
// - fileReceiver 文件配置结果
|
|
// - envFileList 环境变量文件路径, 可以指定多个环境变量文件, 不指定默认加载服务运行目录下 .env 文件
|
|
// - configFilePath 配置文件目录
|
|
// - configFileNameList 配置文件列表
|
|
func Init(configReceiver any, cliReceiver any, envReceiver any, fileReceiver any, envFileList []string, configFilePath string, configFileNameList []string) error {
|
|
var (
|
|
err error
|
|
)
|
|
|
|
if len(envFileList) == 0 {
|
|
envFileList = []string{".env"}
|
|
}
|
|
|
|
if nil != envFileList {
|
|
// 加载环境变量
|
|
if err = godotenv.Load(envFileList...); nil != err {
|
|
return err
|
|
}
|
|
if err = env.Parse(envReceiver); nil != err {
|
|
return errors.New("env param parse fail : " + err.Error())
|
|
}
|
|
}
|
|
|
|
if nil != fileReceiver && len(configFileNameList) > 0 {
|
|
// 读取配置文件内容
|
|
for _, itemConfigFileName := range configFileNameList {
|
|
configFile := filepath.Join(configFilePath, itemConfigFileName)
|
|
if err = serialize.File.ReadAnyFileContent(configFile, &fileReceiver); nil != err {
|
|
return errors.New(configFile + " -> parse config file fail : " + err.Error())
|
|
}
|
|
}
|
|
|
|
}
|
|
// 解析命令行参数
|
|
if _, err = flags.Parse(cliReceiver); nil != err {
|
|
return err
|
|
}
|
|
if err = serialize.JSON.MergeDataForReceiver(configReceiver, fileReceiver, envReceiver, configReceiver); nil != err {
|
|
return errors.New("merge config data fail : " + err.Error())
|
|
}
|
|
return nil
|
|
}
|