参考资料

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 config

import (
    "github.com/mitchellh/mapstructure"
    "github.com/spf13/viper"
    "log"
    "os"
)

// CustomT CustomT
type Mysql struct {
    DNS string `yaml:"dns"`
}

type SqlServer struct {
    DNS string `yaml:"dns"`
}

// CustomT CustomT
type CustomT struct {
    Mysql     Mysql     `yaml:"mySql"`
    SqlServer SqlServer `yaml:"sqlServer"`
}

// Custom Custom
var Custom CustomT

// ReadConfig ReadConfig for custom
func 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 InitConfig
func 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 config

import (
    "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)
}

一曲长歌一剑天涯
3 声望3 粉丝