91 lines
2.1 KiB
Go
91 lines
2.1 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"
|
|
envParse "github.com/caarlos0/env/v9"
|
|
"github.com/jessevdk/go-flags"
|
|
"github.com/joho/godotenv"
|
|
"reflect"
|
|
)
|
|
|
|
// Init 初始化配置
|
|
//
|
|
// Author : go_developer@163.com<白茶清欢>
|
|
//
|
|
// Date : 16:25 2024/11/5
|
|
//
|
|
// 参数:
|
|
// - configReceiver 接收参数结果的指针
|
|
// - envFileList 环境变量文件路径, 可以指定多个环境变量文件, 不指定默认加载服务运行目录下 .env 文件
|
|
// - configFile 配置文件路径
|
|
func Init(configReceiver any, envFileList []string, configFile string) error {
|
|
var (
|
|
err error
|
|
)
|
|
|
|
if nil == envFileList {
|
|
envFileList = make([]string, 0)
|
|
}
|
|
|
|
// 检查结构体指针是否合法
|
|
if err = checkConfigReceiver(configReceiver); err != nil {
|
|
return err
|
|
}
|
|
|
|
// 加载环境变量
|
|
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 {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// 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()
|
|
}
|