funcread() { viper.SetConfigName("config") // name of config file (without extension) viper.SetConfigType("yaml") // REQUIRED if the config file does not have the extension in the name viper.AddConfigPath("/etc/appname/") // path to look for the config file in viper.AddConfigPath("$HOME/.vipertest") // call multiple times to add many search paths viper.AddConfigPath(".") // optionally look for config in the working directory 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(viper.Get("Hacker")) fmt.Println(viper.Get("name")) }
funcreadByIo() { viper.SetConfigType("yaml") // or viper.SetConfigType("YAML") // any approach to require this configuration into your program. var yamlExample = []byte(` Hacker: true name: steve hobbies: - skateboarding - snowboarding - go clothing: jacket: leather trousers: denim age: 35 eyes : brown beard: true `) viper.ReadConfig(bytes.NewBuffer(yamlExample)) name := viper.Get("name") // this would be "steve" fmt.Println(name) fmt.Printf("read by io, name: %s\n", name) }
funcgetValue(key string)string { // 需要强转 //value := viper.Get(key) value := viper.GetString(key) fmt.Printf("get value: %s\n", value) return value }
funcwrite() { // 获取一个key为name的值 value := getValue("name") fmt.Printf("set value: %s\n", value) // set 新值到文件 viper.Set("name", "liukai") value2 := getValue("name") fmt.Printf("set new value2: %s\n", value2)