mycommon/myconf/conf.go

67 lines
1.1 KiB
Go
Raw Normal View History

2023-01-15 00:21:08 +08:00
package myconf
import (
"fmt"
2024-07-19 15:26:51 +08:00
"github.com/spf13/pflag"
2023-01-15 00:21:08 +08:00
"github.com/spf13/viper"
2024-07-19 15:26:51 +08:00
"log"
2023-01-15 00:21:08 +08:00
)
2024-07-19 15:26:51 +08:00
type Config struct {
*viper.Viper
}
2024-06-20 11:00:14 +08:00
var (
2024-07-19 15:26:51 +08:00
conf = &Config{Viper: viper.New()}
2024-06-20 11:00:14 +08:00
)
2024-07-19 15:26:51 +08:00
// 加载命令行参数
func LoadFlag() {
if !pflag.Parsed() {
pflag.Parse()
}
err := conf.BindPFlags(pflag.CommandLine)
2023-01-15 00:21:08 +08:00
if err != nil {
2024-07-19 15:26:51 +08:00
panic(fmt.Errorf("load command line fail: %s", err))
2023-01-15 00:21:08 +08:00
}
2024-07-19 15:26:51 +08:00
}
2024-06-20 11:00:14 +08:00
2024-07-19 15:26:51 +08:00
// 指定文件加载
func LoadFile(confFile string) {
log.Printf("read conf file: %s", confFile)
conf.SetConfigFile(confFile)
err := conf.ReadInConfig()
2023-01-15 00:21:08 +08:00
if err != nil {
2024-07-19 15:26:51 +08:00
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
2023-01-15 00:21:08 +08:00
}
2024-07-19 15:26:51 +08:00
return v
2023-01-15 00:21:08 +08:00
}
2024-06-20 11:00:14 +08:00
2024-07-19 15:26:51 +08:00
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)
2024-06-20 11:00:14 +08:00
}