更多补充: https://www.liwenzhou.com/posts/Go/viper_tutorial/
1 简介
- 读取 json,toml,ini,yaml,hcl,env 等格式的文件内容
- 读取远程配置文件,如 consul,etcd 等和监控配置文件变化
- 读取命令行 flag 的值
- 从 buffer 中读取值
- 读取 环境变量
2 将配置文件映射为struct
(1) xxx.yaml
```yaml name: “go-web”
mysql: host: 127.0.0.1 port: 8021
<a name="agadS"></a>## (2) main.go```gopackage mainimport ("fmt""github.com/fsnotify/fsnotify""github.com/spf13/viper")type MySqlConfig struct {Host string `mapstructure:"host"`Port int `mapstructure:"port"`}type ServerConfig struct {ServiceName string `mapstructure:"name"`MysqlInfo MySqlConfig `mapstructure:"mysql"`}func main() {v := viper.New()v.SetConfigFile("./xxx.yaml")if err := v.ReadInConfig(); err != nil {panic(err)}serverConfig := ServerConfig{}if err := v.Unmarshal(&serverConfig); err != nil {panic(err)}fmt.Println(serverConfig) // {go-web 8021}// 监视配置文件变化v.WatchConfig()v.OnConfigChange(func(e fsnotify.Event) {fmt.Println("config file changed", e.Name)_ = v.ReadInConfig()_ = v.Unmarshal(&serverConfig)})select {} // 一直阻塞在这儿}
