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.
 
 

73 lines
1.6 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.Replace(fileName, ext, "", -1)
confType = strings.Replace(ext, ".", "", 1)
return
}
func MustLoadConfig[T any](conf T, confPathArg ...string) T {
err := LoadConfig(conf, confPathArg...)
if err != nil {
panic(err)
}
return conf
}
// LoadConfig load config.toml
// appConf service custom config
// return common service configuration
func LoadConfig[T any](conf T, confPathArg ...string) error {
confPath := ""
confName := "config"
confType := "toml"
envPrefix := "SO"
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 errors.New("viper read config fail: " + err.Error())
}
if err := v.Unmarshal(conf); err != nil {
return errors.New("viper unmarshal config failed: " + err.Error())
}
return nil
}