Go Viper

Go Viper

什么是viper

快速入门

安装
go get github.com/spf13/viper
读取配置
package main

import (
	"fmt"
	"github.com/spf13/viper"
)

func main() {
	viper.SetConfigName("config") // 配置文件名
	viper.SetConfigType("yaml")   // 配置后缀
	viper.AddConfigPath(".")      // 配置路径
	err := viper.ReadInConfig()   // Find and read the config file

	if err != nil { // Handle errors reading the config file
		panic(fmt.Errorf("fatal error config file: %w", err))
	}
	fmt.Println("==============取值==============")
	fmt.Println(viper.AllSettings())  //map[db:map[authsource:admin host:localhost name:test password:root poolsize:10 port:27017 type:mongodb user:root]]
	fmt.Println(viper.Get("db"))      // map[authsource:admin host:localhost name:test password:root poolsize:10 port:27017 type:mongodb user:root]
	fmt.Println(viper.Get("db.type")) // mongodb

}

动态监听yaml配置文件变更
package main

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)

func main() {
	viper.SetConfigName("config") // 配置文件名
	viper.SetConfigType("yaml")   // 配置后缀
	viper.AddConfigPath(".")      // 配置路径
	err := viper.ReadInConfig()   // Find and read the config file

	if err != nil { // Handle errors reading the config file
		panic(fmt.Errorf("fatal error config file: %w", err))
	}
	fmt.Println("==============取值==============")
	fmt.Println(viper.AllSettings())  //map[db:map[authsource:admin host:localhost name:test password:root poolsize:10 port:27017 type:mongodb user:root]]
	fmt.Println(viper.Get("db"))      // map[authsource:admin host:localhost name:test password:root poolsize:10 port:27017 type:mongodb user:root]
	fmt.Println(viper.Get("db.type")) // mongodb

	// 监听配置文件变化
	viper.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("Config file changed:", e.Name)
		fmt.Println("新配置值:", viper.AllSettings())
	})

	viper.WatchConfig()

	// 通过一个永远不会收到数据的 channel 阻塞主 goroutine
	done := make(chan struct{})
	<-done // <-done 会一直阻塞,等待从 done channel 接收数据。
}

image-20250323220813275

posted @ 2026-03-15 23:30  染指未来  阅读(22)  评论(0)    收藏  举报