package main import ( "fmt" "github.com/fsnotify/fsnotify" "github.com/spf13/viper" ) func main() { // 读取配置文件 viper.SetConfigName("config") viper.SetConfigType("yaml") viper.AddConfigPath(".") if err := viper.ReadInConfig(); err != nil { panic(err) } fmt.Println("Initial config loaded") fmt.Printf("App Name: %s\n", viper.GetString("app.name")) fmt.Printf("App Port: %d\n", viper.GetInt("app.port")) // 监听配置文件变化 viper.WatchConfig() viper.OnConfigChange(func(in fsnotify.Event) { fmt.Println("\n--- Config file changed! ---") fmt.Printf("Event: %s\n", in.Op.String()) fmt.Printf("File: %s\n", in.Name) fmt.Printf("App Name: %s\n", viper.GetString("app.name")) fmt.Printf("App Port: %d\n", viper.GetInt("app.port")) }) fmt.Println("\nWatching for config changes... (modify config.yaml to see changes)") fmt.Println("Press Ctrl+C to exit") // 保持程序运行 select {} }