viper.go 1.2 KB

1234567891011121314151617181920212223242526272829303132
  1. package initialize
  2. import (
  3. "github.com/RaymondCode/simple-demo/config"
  4. "github.com/spf13/viper"
  5. "log"
  6. )
  7. func Viper() {
  8. //viper.SetConfigType("yaml") // 如果配置文件的名称中没有扩展名,则需要配置此项
  9. //viper.AddConfigPath("./vipertest/") // 设置读取路径:就是在此路径下搜索配置文件。
  10. var conf = config.SystemConf{}
  11. //viper.AddConfigPath("$HOME/.appname") // 多次调用以添加多个搜索路径
  12. viper.SetConfigFile("./config/application.yaml") // 设置被读取文件的全名,包括扩展名。
  13. //viper.SetConfigName("server") // 设置被读取文件的名字: 这个方法 和 SetConfigFile实际上仅使用一个就够了
  14. viper.ReadInConfig() // 读取配置文件: 这一步将配置文件变成了 Go语言的配置文件对象包含了 map,string 等对象。
  15. err := viper.Unmarshal(&conf)
  16. config.CONFIG = conf
  17. if err != nil {
  18. log.Panic("viper反序列化错误")
  19. }
  20. username := conf.OssConfig.Key
  21. password := conf.OssConfig.Secret
  22. log.Println(username + " " + password)
  23. log.Println(conf.SnowFlakeConfig.MechineId)
  24. // fmt.Printf("%+v",conf)
  25. // 控制台输出: map[first:panda last:8z] 99 panda [Coding Movie Swimming]
  26. }