update
This commit is contained in:
@@ -2,27 +2,65 @@ package myconf
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/spf13/pflag"
|
||||
"github.com/spf13/viper"
|
||||
"log"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
*viper.Viper
|
||||
}
|
||||
|
||||
var (
|
||||
vp *viper.Viper
|
||||
conf = &Config{Viper: viper.New()}
|
||||
)
|
||||
|
||||
func Init(confPath string, conf interface{}) {
|
||||
vp = viper.New()
|
||||
vp.SetConfigFile(confPath)
|
||||
err := vp.ReadInConfig()
|
||||
if err != nil {
|
||||
panic(fmt.Errorf("读取配置文件失败 %s", err))
|
||||
// 加载命令行参数
|
||||
func LoadFlag() {
|
||||
if !pflag.Parsed() {
|
||||
pflag.Parse()
|
||||
}
|
||||
|
||||
err = vp.Unmarshal(conf)
|
||||
err := conf.BindPFlags(pflag.CommandLine)
|
||||
if err != nil {
|
||||
panic(fmt.Errorf("解析配置文件失败 %s", err))
|
||||
panic(fmt.Errorf("load command line fail: %s", err))
|
||||
}
|
||||
}
|
||||
|
||||
func Conf() *viper.Viper {
|
||||
return vp
|
||||
// 指定文件加载
|
||||
func LoadFile(confFile string) {
|
||||
log.Printf("read conf file: %s", confFile)
|
||||
|
||||
conf.SetConfigFile(confFile)
|
||||
err := conf.ReadInConfig()
|
||||
if err != nil {
|
||||
panic(fmt.Errorf("read file fail: %s", err))
|
||||
}
|
||||
}
|
||||
|
||||
func Conf() *Config {
|
||||
return conf
|
||||
}
|
||||
|
||||
func (c *Config) GetStringDefault(key, defaultVal string) string {
|
||||
v := c.GetString(key)
|
||||
if v == "" {
|
||||
return defaultVal
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func (c *Config) GetIntDefault(key string, defaultVal int) int {
|
||||
v := c.GetString(key) // 未设置 空字符串
|
||||
if v == "" {
|
||||
return defaultVal
|
||||
}
|
||||
return c.GetInt(key)
|
||||
}
|
||||
|
||||
func (c *Config) GetBoolDefault(key string, defaultVal bool) bool {
|
||||
v := c.GetString(key) // 未设置 空字符串
|
||||
if v == "" {
|
||||
return defaultVal
|
||||
}
|
||||
return c.GetBool(key)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user