viper-app/cmd/init/conf.go

116 lines
3.0 KiB
Go

package init
import (
"demo-server/internal/config"
"demo-server/internal/model"
"demo-server/pkg/str"
"encoding/json"
"fmt"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
"go.uber.org/zap"
"os"
"strings"
)
func initConfigWarpDefault() (err error) {
if err = initConfig(); err == nil {
return
}
println("[warning] boot from [" + cfgPath + "] err: " + err.Error() + ", system will retry default config")
const defaultConf = "./default/application.yaml"
cfgPath = defaultConf
if err = initConfig(); err == nil {
defer func() {
if r := recover(); r != nil {
zap.L().Error("init panic", zap.Any("recover", r))
}
}()
}
return
}
func initConfig() (err error) {
if cfgPath != "" {
// Use config file from the flag.
viper.AddConfigPath(cfgPath)
} else {
var workdir string
// Find workdir.
workdir, err = os.Getwd()
if err != nil {
return err
}
// set default config file $PWD/conf/application.yml
viper.AddConfigPath(workdir + model.ConfigFilePath)
}
viper.SetConfigType(model.ConfigType)
viper.SetConfigName(model.ConfigName)
configDefault()
configWatch()
viper.AutomaticEnv() // read in environment variables that match
// If a config file is found, read it in.
if err = viper.ReadInConfig(); err != nil {
return
}
if err = viper.Unmarshal(config.Get()); err != nil {
return
}
cfgData, _ := json.Marshal(config.Get())
println("read config ->", str.B2S(cfgData))
svr := config.Get().Svr
if strings.HasPrefix(svr.Address, ":") {
svr.Address = "0.0.0.0" + svr.Address
}
return err
}
func configDefault() {
// // server
// viper.SetDefault("server.address", model.DefaultServerAddress)
//
// // file
// viper.SetDefault("file.root", model.DefaultFSRoot)
// viper.SetDefault("file.prefix_upload", model.DefaultFSUploadPrefix)
//
// // db
// viper.SetDefault("db.type", db.TypeSQLITE)
// viper.SetDefault("db.dsn", model.DefaultDBDSN)
// viper.SetDefault("db.log_level", model.DefaultDBLogLevel)
//
// // kafka
// viper.SetDefault("kafka.producer.batch_size", model.DefaultKafkaBatchSize)
// viper.SetDefault("kafka.producer.batch_bytes", model.DefaultKafkaBatchByte)
// viper.SetDefault("kafka.chunk_size", model.DefaultKafkaChunkSize)
// viper.SetDefault("kafka.block_size", model.DefaultKafkaBlockSize)
//
// viper.SetDefault("prometheus.push_gateway", model.DefaultPromPushGateway)
// viper.SetDefault("prometheus.interval", model.DefaultPromInterval)
//
// viper.SetDefault("async.offline_interval", model.DefaultOfflineInterval)
// viper.SetDefault("async.offline_threshold", model.DefaultOfflineThreshold)
//
}
func configWatch() {
viper.OnConfigChange(func(in fsnotify.Event) {
eventString := fmt.Sprintf("%s -> `%s`", in.Op, in.Name)
zap.L().Info("config file change", zap.String("event", eventString))
if err := viper.Unmarshal(config.Get()); err != nil {
zap.L().Info("save config err!", zap.Error(err))
}
//server.GetSvr().Dispatch(model.GetConfig())
})
viper.WatchConfig()
}