package main
import (
"fmt"
"github.com/fsnotify/fsnotify"
"github.com/spf13/viper"
"log"
"time"
)
type settings struct {
Application *application
}
type application struct {
mode string
host string
name string
port int64
enabledp bool
}
func main() {
//设置要读取配置文件的名字
viper.SetConfigName("config")
//配置文件格式 yaml 也可以支持json等格式,按需设置
//viper.SetConfigType("json")
viper.SetConfigType("yaml")
viper.AddConfigPath("./") // 查找配置文件的路径。
//viper.AddConfigPath("$HOME/.appname") // 多次调用以添加许多搜索路径
//也可以设置默认值
viper.SetDefault("settings.application.pwd", 1324)
//开始载入配置文件
err := viper.ReadInConfig()
if err != nil {
log.Fatal("read config failed: %v", err)
}
viper.WatchConfig()
go func() {
viper.OnConfigChange(func(e fsnotify.Event) {
log.Printf("Config file changed: %s", e.Name)
})
}()
go func() {
for {
viper.Set("app_name", "123")
time.Sleep(time.Second * 2)
}
}()
//查看配置文件
fmt.Println(viper.Get("app_name"))
_cfg := &settings{
Application: &application{},
}
if err := viper.Unmarshal(&_cfg); err != nil {
fmt.Println(err)
}
fmt.Println("所有的key: ")
for _, k := range viper.AllKeys() {
fmt.Println(k)
}
fmt.Println("所有的config: \n", viper.AllSettings())
select {}
}
config.yaml
{
"app_name" : "asdf",
"log_level": "height",
"redis" : {
"host" : "127.0.0.1",
"port" : 6379
},
"mysql" : {
"host" : "192.168.0.133",
"user" : "adf",
"password" : "xxxxx",
"port" : 3306,
"database" : "test"
}
}