package main import ( "fmt" "github.com/spf13/viper" ) func main() { // 1. 设置配置文件名和路径 viper.SetConfigName("config") // 配置文件名(不含扩展名) viper.SetConfigType("yaml") // 配置文件类型 viper.AddConfigPath(".") // 配置文件路径 // 2. 读取配置文件 if err := viper.ReadInConfig(); err != nil { panic(fmt.Errorf("Fatal error config file: %s", err)) } fmt.Println("Config file loaded successfully!") // 3. 读取单个配置项 appName := viper.GetString("app.name") appPort := viper.GetInt("app.port") fmt.Printf("App Name: %s\n", appName) fmt.Printf("App Port: %d\n", appPort) // 4. 读取嵌套配置 dbHost := viper.GetString("database.host") dbPort := viper.GetInt("database.port") fmt.Printf("Database: %s:%d\n", dbHost, dbPort) // 5. 读取所有配置 allSettings := viper.AllSettings() fmt.Printf("All settings: %v\n", allSettings) }