mycommon/myconf/conf.go

47 lines
761 B
Go
Raw Normal View History

2023-01-15 00:21:08 +08:00
package myconf
import (
"fmt"
2024-06-23 13:15:47 +08:00
"github.com/spf13/pflag"
2023-01-15 00:21:08 +08:00
"github.com/spf13/viper"
)
2024-06-20 11:00:14 +08:00
var (
2024-06-23 11:32:45 +08:00
vp = viper.New()
2024-06-20 11:00:14 +08:00
)
2024-06-23 13:15:47 +08:00
func LoadFlag() {
2024-06-23 13:26:48 +08:00
if !pflag.Parsed() {
pflag.Parse()
}
2024-06-23 13:15:47 +08:00
err := vp.BindPFlags(pflag.CommandLine)
if err != nil {
panic(fmt.Errorf("load command line fail: %s", err))
}
}
2024-06-23 14:24:25 +08:00
func LoadFile(confFile string) {
vp.SetConfigFile(confFile)
err := vp.ReadInConfig()
if err != nil {
panic(fmt.Errorf("read file fail: %s", err))
}
}
func LoadFileTo(confFile string, conf interface{}) {
2024-06-23 11:32:45 +08:00
vp.SetConfigFile(confFile)
2024-06-20 11:00:14 +08:00
err := vp.ReadInConfig()
2023-01-15 00:21:08 +08:00
if err != nil {
2024-06-23 11:32:45 +08:00
panic(fmt.Errorf("read file fail: %s", err))
2023-01-15 00:21:08 +08:00
}
2024-06-20 11:00:14 +08:00
err = vp.Unmarshal(conf)
2023-01-15 00:21:08 +08:00
if err != nil {
2024-06-23 11:32:45 +08:00
panic(fmt.Errorf("parse file fail: %s", err))
2023-01-15 00:21:08 +08:00
}
}
2024-06-20 11:00:14 +08:00
func Conf() *viper.Viper {
return vp
}