86 lines
1.8 KiB
Go
86 lines
1.8 KiB
Go
package cmd
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"github.com/fsnotify/fsnotify"
|
|
"github.com/spf13/viper"
|
|
"go.uber.org/zap"
|
|
"os"
|
|
"packet-ui/internal/model"
|
|
"packet-ui/internal/server"
|
|
"packet-ui/pkg"
|
|
"packet-ui/pkg/db"
|
|
"strings"
|
|
)
|
|
|
|
func InitConfig() (err error) {
|
|
if cfgFile != "" {
|
|
// Use config file from the flag.
|
|
viper.SetConfigFile(cfgFile)
|
|
} 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 + "/conf")
|
|
viper.SetConfigType("yaml")
|
|
viper.SetConfigName("application")
|
|
}
|
|
|
|
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(model.GetConfig()); err != nil {
|
|
return
|
|
}
|
|
|
|
cfgData, _ := json.Marshal(model.GetConfig())
|
|
println("config", pkg.B2S(cfgData))
|
|
|
|
svr := model.GetConfig().Svr
|
|
if strings.HasPrefix(svr.Address, ":") {
|
|
svr.Address = "0.0.0.0" + svr.Address
|
|
}
|
|
//defer func() {
|
|
// if e := viper.WriteConfig(); e != nil {
|
|
// zap.L().Warn("save config err!", zap.Error(e))
|
|
// }
|
|
//}()
|
|
|
|
return err
|
|
}
|
|
|
|
func configDefault() {
|
|
// db
|
|
viper.SetDefault("db.type", db.TypeSQLITE)
|
|
viper.SetDefault("db.dsn", "./packet-ui.db")
|
|
|
|
// file
|
|
viper.SetDefault("file.data", "./data/root")
|
|
|
|
// viper.
|
|
}
|
|
|
|
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(model.GetConfig()); err != nil {
|
|
zap.L().Info("save config err!", zap.Error(err))
|
|
}
|
|
server.GetSvr().Dispatch(model.GetConfig())
|
|
})
|
|
viper.WatchConfig()
|
|
}
|