// Author: Mjy
// Create Date: 2018-11-23
package config
import (
"fmt"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
"strings"
)
type ApiConfig struct {
RunMode string `mapstructure:"runmode"`
Addr string `mapstructure:"addr"`
Port int `mapstructure:"port"`
Name string `mapstructure:"name"`
Url string `mapstructure:"url"`
MaxPingCount int `mapstructure:"max_ping_count"`
}
var Config = &ApiConfig{}
func InitConfig(cfg string) error {
c := viper.New()
if err := initConfig(cfg, c); err != nil {
return err
}
if err := c.UnmarshalExact(Config); err != nil {
return err
}
c.WatchConfig()
c.OnConfigChange(func(e fsnotify.Event) {
fmt.Println("Config file changed:" + e.Name)
c.Unmarshal(Config)
})
return nil
}
func initConfig(cfg string, c *viper.Viper) error {
c.SetConfigType("yaml")
if cfg == "" {
c.SetConfigFile("/Users/majianyu/Code/go/GoLandProjects/dsers/src/api/conf/config.yaml")
} else {
c.SetConfigFile(cfg)
}
c.AutomaticEnv()
c.SetEnvPrefix("APISERVER")
replacer := strings.NewReplacer(".", "_")
c.SetEnvKeyReplacer(replacer)
if err := c.ReadInConfig(); err != nil {
return err
}
return nil
}