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 (
|
2024-11-05 18:04:27 +08:00
|
|
|
"errors"
|
2024-11-05 18:20:20 +08:00
|
|
|
"git.zhangdeman.cn/zhangdeman/serialize"
|
|
|
|
envParse "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-05 18:04:27 +08:00
|
|
|
"reflect"
|
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
|
|
|
//
|
|
|
|
// 参数:
|
|
|
|
// - configReceiver 接收参数结果的指针
|
|
|
|
// - envFileList 环境变量文件路径, 可以指定多个环境变量文件, 不指定默认加载服务运行目录下 .env 文件
|
|
|
|
// - configFile 配置文件路径
|
|
|
|
func Init(configReceiver any, envFileList []string, configFile string) error {
|
2024-11-05 17:06:26 +08:00
|
|
|
var (
|
|
|
|
err error
|
|
|
|
)
|
|
|
|
|
2024-11-05 18:20:20 +08:00
|
|
|
if nil == envFileList {
|
|
|
|
envFileList = make([]string, 0)
|
|
|
|
}
|
|
|
|
|
|
|
|
// 检查结构体指针是否合法
|
2024-11-05 18:04:27 +08:00
|
|
|
if err = checkConfigReceiver(configReceiver); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2024-11-05 18:20:20 +08:00
|
|
|
// 加载环境变量
|
|
|
|
if err = godotenv.Load(envFileList...); nil != err {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
// 解析命令行参数
|
|
|
|
cliReceiver := cloneReceiver(configReceiver)
|
|
|
|
if _, err = flags.Parse(cliReceiver); nil != err {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
// 解析环境变量参数
|
|
|
|
envReceiver := cloneReceiver(configReceiver)
|
|
|
|
if err = envParse.Parse(envReceiver); nil != err {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
// 解析配置文件参数
|
|
|
|
fileReceiver := cloneReceiver(configReceiver)
|
|
|
|
if err = serialize.File.ReadAnyFileContent(configFile, fileReceiver); nil != err {
|
2024-11-05 17:06:26 +08:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
2024-11-05 18:04:27 +08:00
|
|
|
|
|
|
|
// checkConfigReceiver 校验配置接收者必须是指针
|
|
|
|
//
|
|
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
|
|
//
|
|
|
|
// Date : 17:16 2024/11/5
|
|
|
|
func checkConfigReceiver(configReceiver any) error {
|
|
|
|
if nil == configReceiver {
|
|
|
|
return errors.New("config receiver is nil")
|
|
|
|
}
|
|
|
|
receiverType := reflect.TypeOf(configReceiver)
|
|
|
|
if receiverType.Kind() != reflect.Ptr {
|
|
|
|
return errors.New("config receiver is not a pointer")
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// cloneReceiver ...
|
|
|
|
//
|
|
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
|
|
//
|
|
|
|
// Date : 17:16 2024/11/5
|
|
|
|
func cloneReceiver(configReceiver any) any {
|
|
|
|
dataType := reflect.TypeOf(configReceiver).Elem()
|
|
|
|
return reflect.New(dataType).Interface()
|
|
|
|
}
|