golang viper 使用 错误集

package main

import (
	"fmt"
	"github.com/fsnotify/fsnotify"
	"github.com/gin-gonic/gin"
	"github.com/spf13/viper"
	"net/http"
)

func main() {
	//viper.SetDefault("coentdir", "conent")
	//res := viper.Get("coentdir")
	//fmt.Printf("coentdir:%#v
", res)

	//viper.SetConfigFile("./config.yaml") // 指定配置文件路径
	viper.SetConfigName("config")      // 配置文件名称(无扩展名)
	viper.SetConfigType("yaml")        // 如果配置文件的名称中没有扩展名,则需要配置此项
	viper.SetConfigFile("config.yaml") // 直接设置详细的文件信息
	//viper.AddConfigPath("/etc/appname/")  // 查找配置文件所在的路径
	//viper.AddConfigPath("$HOME/.appname") // 多次调用以添加多个搜索路径

	viper.AddConfigPath("./")   // 还可以在工作目录中查找配置
	err := viper.ReadInConfig() // 查找并读取配置文件
	if err != nil {             // 处理读取配置文件的错误
		panic(fmt.Errorf("Fatal error config file: %s 
", err))
	}

	// 读取配置文件之后 可以加一个实时监控文件变化
	viper.WatchConfig()

	// 当配置变化之后,做一个回调函数
	viper.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("config file changed:", e.Name)

	})

	r := gin.Default()
	r.GET("/version", func(c *gin.Context) {
		c.String(http.StatusOK, viper.GetString("version"))

	})

	r.Run(":8889")

}

  

golang 使用viper 配置的时候,报以下错误:

panic: Fatal error config file: While parsing config: yaml: line 3: mapping values are not allowed in this context 


goroutine 1 [running]:
main.main()
	C:/goweb study/viper_demo/main.go:26 +0x35d

  

错误原因是因为 yaml 文件中的,键值对 :之后没有加空格 导致的。加上空格再试下就OK了。

 加上空格 搞定。

viper 读取配置文件例子

package main

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

/*
database:
  thing_model_db:
    driver: mysql
    name: db_ting_model
    host: 127.0.0.1
    user: XXX
    password: XXX
    port: 3306
    timeout: 1
*/

// 配置信息

type DemoConfig struct {
	AppConfig      `mapstructure:"app"`
	DatabaseConfig `mapstructure:"database"`
}

type AppConfig struct {
	Version string `mapstructure:"version"`
	Name    string `mapstructure:"name"`
}
type DatabaseConfig struct {
	Driver   string `mapstructure:"driver"`
	Name     string `mapstructure:"name"`
	Host     string `mapstructure:"host"`
	User     string `mapstructure:"user"`
	Password string `mapstructure:"password"`
	Port     string `mapstructure:"port"`
}

func main() {

	viper.SetConfigFile("./config.yaml")  // 指定配置文件路径
	viper.SetConfigName("config")         // 配置文件名称(无扩展名)
	viper.SetConfigType("yaml")           // 如果配置文件的名称中没有扩展名,则需要配置此项
	viper.AddConfigPath("/etc/appname/")  // 查找配置文件所在的路径
	viper.AddConfigPath("$HOME/.appname") // 多次调用以添加多个搜索路径
	viper.AddConfigPath(".")              // 还可以在工作目录中查找配置
	err := viper.ReadInConfig()           // 查找并读取配置文件
	if err != nil {                       // 处理读取配置文件的错误
		panic(fmt.Errorf("Fatal error config file: %s 
", err))
	}


	// 实时监控配置文件
	viper.WatchConfig()

	viper.OnConfigChange(func(e fsnotify.Event) {
		fmt.Println("config file changed :",e.Name)

	})

	// 实例化变量
	var c DemoConfig
	if err := viper.Unmarshal(&c);err != nil {
		fmt.Printf(" viper.Unmarshal failed, err %v
",err )
		return
	}
	
	
	// 答应读取的变量信息
	fmt.Printf("c:%#v",c)

}

/*
c:main.DemoConfig{AppConfig:main.AppConfig{Version:"1", Name:"iot_thing_model"}, DatabaseConfig:main.DatabaseConfig{Driver:"mysql", Name:"db_ting_model", Host:"127.0.0.1", User:"root", Password:"123456", Port:"3306"}}
Process finished with exit code 0

*/

  

原文地址:https://www.cnblogs.com/zexin88/p/14502976.html