config/init.go

71 lines
2.0 KiB
Go
Raw Normal View History

2024-11-05 17:06:26 +08:00
// Package config ...
//
// Description : config ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2024-11-05 16:23
package config
import (
"errors"
2024-11-05 18:20:20 +08:00
"git.zhangdeman.cn/zhangdeman/serialize"
2024-11-08 14:54:32 +08:00
"github.com/caarlos0/env/v9"
2024-11-05 17:06:26 +08:00
"github.com/jessevdk/go-flags"
2024-11-05 18:20:20 +08:00
"github.com/joho/godotenv"
2024-11-08 14:54:32 +08:00
"path/filepath"
2024-11-05 17:06:26 +08:00
)
// Init 初始化配置
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:25 2024/11/5
2024-11-05 18:20:20 +08:00
//
// 参数:
2024-11-08 14:54:32 +08:00
// - configReceiver 接收最终配置结果的指针
// - cliReceiver 命令函参数配置结果
// - envReceiver 环境变量配置结果
// - fileReceiver 文件配置结果
2024-11-05 18:20:20 +08:00
// - envFileList 环境变量文件路径, 可以指定多个环境变量文件, 不指定默认加载服务运行目录下 .env 文件
2024-11-08 14:54:32 +08:00
// - configFilePath 配置文件目录
// - configFileNameList 配置文件列表
func Init(configReceiver any, cliReceiver any, envReceiver any, fileReceiver any, envFileList []string, configFilePath string, configFileNameList []string) error {
2024-11-05 17:06:26 +08:00
var (
2024-11-08 14:54:32 +08:00
err error
2024-11-05 17:06:26 +08:00
)
2024-11-08 14:54:32 +08:00
if len(envFileList) == 0 {
envFileList = []string{".env"}
2024-11-05 18:20:20 +08:00
}
2024-11-08 14:54:32 +08:00
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())
}
}
2024-11-08 14:54:32 +08:00
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())
}
}
2024-11-05 18:20:20 +08:00
}
2024-11-08 14:54:32 +08:00
// 解析命令行参数
if _, err = flags.Parse(cliReceiver); nil != err {
2024-11-05 18:20:20 +08:00
return err
}
2024-11-08 14:54:32 +08:00
if err = serialize.JSON.MergeDataForReceiver(configReceiver, fileReceiver, envReceiver, configReceiver); nil != err {
return errors.New("merge config data fail : " + err.Error())
2024-11-05 17:06:26 +08:00
}
return nil
}