12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485 |
- package config
- import (
- "github.com/spf13/cast"
- viperLib "github.com/spf13/viper"
- "path"
- "rinne.dev/doh-resolver/pkg/helpers"
- )
- // viper 库实例
- var viper *viperLib.Viper
- func init() {
- viper = viperLib.New()
- viper.SetConfigType("yaml")
- }
- // InitConfig 初始化配置信息
- func InitConfig(filePath string) {
- // 加载配置文件
- viper.SetConfigName(path.Base(filePath))
- viper.AddConfigPath(path.Dir(filePath))
- if err := viper.ReadInConfig(); err != nil {
- panic(err)
- }
- // 监控配置文件,变更时重新加载
- viper.WatchConfig()
- }
- // Get 获取配置项
- func Get(path string, defaultValue ...interface{}) string {
- return GetString(path, defaultValue...)
- }
- func internalGet(path string, defaultValue ...interface{}) interface{} {
- // config 或者环境变量不存在的情况
- if !viper.IsSet(path) || helpers.Empty(viper.Get(path)) {
- if len(defaultValue) > 0 {
- return defaultValue[0]
- }
- return nil
- }
- return viper.Get(path)
- }
- // GetString 获取 String 类型的配置信息
- func GetString(path string, defaultValue ...interface{}) string {
- return cast.ToString(internalGet(path, defaultValue...))
- }
- // GetInt 获取 Int 类型的配置信息
- func GetInt(path string, defaultValue ...interface{}) int {
- return cast.ToInt(internalGet(path, defaultValue...))
- }
- // GetFloat64 获取 float64 类型的配置信息
- func GetFloat64(path string, defaultValue ...interface{}) float64 {
- return cast.ToFloat64(internalGet(path, defaultValue...))
- }
- // GetInt64 获取 Int64 类型的配置信息
- func GetInt64(path string, defaultValue ...interface{}) int64 {
- return cast.ToInt64(internalGet(path, defaultValue...))
- }
- // GetUint 获取 Uint 类型的配置信息
- func GetUint(path string, defaultValue ...interface{}) uint {
- return cast.ToUint(internalGet(path, defaultValue...))
- }
- // GetBool 获取 Bool 类型的配置信息
- func GetBool(path string, defaultValue ...interface{}) bool {
- return cast.ToBool(internalGet(path, defaultValue...))
- }
- // GetStringMapString 获取结构数据
- func GetStringMapString(path string) map[string]string {
- return viper.GetStringMapString(path)
- }
- // GetStringArray 获取字符串数组
- func GetStringArray(path string) []string {
- return cast.ToStringSlice(internalGet(path))
- }
|