Viper 讀取配置
創建一個配置文件?config.yaml
server:port: 8080timeout: 30 # 超時時間(秒)
database:host: "localhost"user: "root"password: "123456"name: "mydb"
然后用 Viper 讀取這個配置,代碼如下:
package mainimport ("fmt""log""github.com/spf13/viper"
)func main() {// 1. 告訴 Viper 配置文件在哪viper.SetConfigFile("config.yaml") // 指定配置文件// 2. 讀取配置文件err := viper.ReadInConfig()if err != nil {log.Fatalf("配置文件讀不了:%v", err)}// 3. 讀取具體配置項serverPort := viper.GetInt("server.port") // 讀服務器端口dbHost := viper.GetString("database.host") // 讀數據庫地址dbPassword := viper.GetString("database.password") // 讀數據庫密碼// 4. 使用配置fmt.Printf("服務器將啟動在 %d 端口\n", serverPort)fmt.Printf("將連接數據庫:%s@%s\n", dbHost, dbPassword)// 5. 演示:設置默認值(如果配置文件沒寫,就用這個)viper.SetDefault("server.debug", false)isDebug := viper.GetBool("server.debug")fmt.Printf("是否開啟調試模式:%v\n", isDebug)
}
動態監聽配置
Viper 支持動態監聽配置文件變化,不用重啟程序就能感知到?config.yaml
?的修改并應用新配置。
package mainimport ("fmt""log""time""github.com/fsnotify/fsnotify""github.com/spf13/viper"
)func main() {// 1. 配置 Viper 讀取 config.yamlviper.SetConfigFile("config.yaml")if err := viper.ReadInConfig(); err != nil {log.Fatalf("無法讀取配置文件: %v", err)}// 2. 打印初始配置printCurrentConfig()// 3. 啟動配置監聽(關鍵代碼)viper.WatchConfig()// 4. 注冊配置變化的回調函數(配置修改后會自動執行)viper.OnConfigChange(func(e fsnotify.Event) {fmt.Println("\n配置文件被修改了!路徑:", e.Name)// 重新打印配置,查看變化printCurrentConfig()})// 讓程序保持運行,方便測試fmt.Println("\n程序正在運行,嘗試修改 config.yaml 看看效果...")for {time.Sleep(time.Second)}
}// 打印當前配置的函數
func printCurrentConfig() {port := viper.GetInt("server.port")debug := viper.GetBool("server.debug")dbHost := viper.GetString("database.host")fmt.Printf("當前配置:端口=%d, 調試模式=%v, 數據庫地址=%s\n", port, debug, dbHost)
}
運行程序,初始會打印配置
不要關閉程序,手動修改 config.yaml 中的內容(比如把 port: 8080 改成 port: 9090)
保存文件后,程序會立刻輸出 "配置文件被修改了",并顯示新的配置值