共计 1263 个字符,预计需要花费 4 分钟才能阅读完成。
参考资料
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)
}
正文完