You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
85 lines
1.9 KiB
85 lines
1.9 KiB
package config |
|
|
|
import ( |
|
"errors" |
|
"fmt" |
|
"os" |
|
"path/filepath" |
|
"sig-pub/pkg/zlog" |
|
"strings" |
|
|
|
"github.com/spf13/viper" |
|
) |
|
|
|
func parseConfPath(confPath string) (filePath, fileName, confType string) { |
|
filePath, fileName = filepath.Split(confPath) |
|
ext := filepath.Ext(fileName) |
|
fileName, _ = strings.CutSuffix(fileName, ext) |
|
confType, _ = strings.CutPrefix(ext, ".") |
|
confType = strings.ToLower(confType) |
|
return |
|
} |
|
|
|
func LoadConfig[T any](conf T, confPathArg ...string) (T, error) { |
|
v, err := loadViper(confPathArg...) |
|
if err != nil { |
|
return conf, err |
|
} |
|
if err := v.Unmarshal(conf); err != nil { |
|
err = errors.New("viper unmarshal config failed: " + err.Error()) |
|
return conf, err |
|
} |
|
return conf, nil |
|
} |
|
|
|
func MustLoadConfig[T any](conf T, confPathArg ...string) T { |
|
v, err := loadViper(confPathArg...) |
|
if err != nil { |
|
panic(err) |
|
} |
|
if err := v.Unmarshal(conf); err != nil { |
|
panic(errors.New("viper unmarshal config failed: " + err.Error())) |
|
} |
|
return conf |
|
} |
|
|
|
// loadViper load config.toml |
|
// appConf service custom config |
|
// return common service configuration |
|
func loadViper(confPathArg ...string) (v *viper.Viper, err error) { |
|
confPath := "" |
|
confName := "config" |
|
confType := "toml" |
|
envPrefix := "SIG" |
|
|
|
if len(confPathArg) > 0 { |
|
confPath = confPathArg[0] |
|
} |
|
|
|
confPath, confName, confType = parseConfPath(confPath) |
|
if confPath == "" { |
|
confPath = "./" |
|
} |
|
|
|
filePath := fmt.Sprintf("%s%s.%s", confPath, confName, confType) |
|
dir, err := os.Getwd() |
|
if err != nil { |
|
zlog.Warning(err) |
|
} else { |
|
filePath = filepath.Join(dir, filePath) |
|
} |
|
zlog.Infof("use config file: %s, env prefix=%s\n", filePath, envPrefix) |
|
|
|
v = viper.New() |
|
v.AddConfigPath(confPath) |
|
v.SetConfigName(confName) |
|
v.SetConfigType(confType) |
|
v.SetEnvPrefix(envPrefix) |
|
v.AutomaticEnv() |
|
v.AllowEmptyEnv(true) |
|
|
|
if err := v.ReadInConfig(); err != nil { |
|
return nil, errors.New("viper read config fail: " + err.Error()) |
|
} |
|
return v, nil |
|
}
|
|
|