参考资料

Golang应用第三方包viper读取yaml配置信息

1. 书写dev_custom.yml文件内容

mySql:  dns: "sqlserver://sa:123456@DESKTOP-HMTA87I:1433?database=wzz"sqlServer:  dns: "me:123abc@tcp(10.0.0.0:3306)/wzz_db?charset=utf8"

2. 解析dev_custom.yml文件内容

package configimport (    "github.com/mitchellh/mapstructure"    "github.com/spf13/viper"    "log"    "os")// CustomT CustomTtype Mysql struct {    DNS string `yaml:"dns"`}type SqlServer struct {    DNS string `yaml:"dns"`}// CustomT CustomTtype CustomT struct {    Mysql     Mysql     `yaml:"mySql"`    SqlServer SqlServer `yaml:"sqlServer"`}// Custom Customvar Custom CustomT// ReadConfig ReadConfig for customfunc ReadConfig(configName string, configPath string, configType string) *viper.Viper {    v := viper.New()    v.SetConfigName(configName)    v.AddConfigPath(configPath)    v.SetConfigType(configType)    err := v.ReadInConfig()    if err != nil {        return nil    }    res := v.AllKeys()    log.Println("res=", res)    return v}// InitConfig InitConfigfunc InitConfig() (err error) {    path, err := os.Getwd()    if err != nil {        return err    }    v := ReadConfig("dev_custom", path, "yml")    md := mapstructure.Metadata{}    err = v.Unmarshal(&Custom, func(config *mapstructure.DecoderConfig) {        config.TagName = "yaml"        config.Metadata = &md    })    return err}

3. 测试

package configimport (    "testing")func TestConfig(t *testing.T) {    err := InitConfig()    if err != nil {        t.Fatal(err)    }    t.Log("mysqlDNS=", Custom.Mysql.DNS)    t.Log("sqlserverDNS=", Custom.SqlServer.DNS)}