golang:第三方库:用vipper解析yaml配置文件
一,安装第三方库
$ go get github.com/spf13/viper
二,代码
1,配置文件
Database:
DBType: mysql
UserName: dbusername
Password: dbpassword
Host: 127.0.0.1:3306
DBName: dbname
Charset: utf8
ParseTime: True
MaxIdleConns: 10
MaxOpenConns: 30
2, 代码:封装:
package setting
import (
"github.com/spf13/viper"
)
type Setting struct {
vp *viper.Viper
}
var sections = make(map[string]interface{})
//读取配置
func NewSetting() (*Setting, error) {
vp := viper.New()
vp.SetConfigName("config")
//vp.AddConfigPath("config")
vp.AddConfigPath(".")
vp.SetConfigType("yaml")
err := vp.ReadInConfig()
if err != nil {
return nil, err
}
s := &Setting{vp}
return s, nil
}
//读取指定的一段
func (s *Setting) ReadSection(k string, v interface{}) error {
err := s.vp.UnmarshalKey(k, v)
if err != nil {
return err
}
if _, ok := sections[k]; !ok {
sections[k] = v
}
return nil
}
//重新加载
func (s *Setting) ReloadAllSection() error {
for k, v := range sections {
err := s.ReadSection(k, v)
if err != nil {
return err
}
}
return nil
}
3,代码:读取到struct中
package config
import (
"fmt"
"industry/pkg/setting"
)
//数据库配置的struct类型
type DatabaseSettingS struct {
DBType string
UserName string
Password string
Host string
DBName string
Charset string
ParseTime bool
MaxIdleConns int
MaxOpenConns int
}
//定义全局变量
var (
DatabaseSetting *DatabaseSettingS
)
//读取配置到全局变量
func SetupSetting() error {
s, err := setting.NewSetting()
if err != nil {
return err
}
err = s.ReadSection("Database", &DatabaseSetting)
if err != nil {
return err
}
fmt.Println("setting:")
//fmt.Println(ServerSetting)
fmt.Println(DatabaseSetting)
return nil
}
4,main.go中做初始化:
func init() {
err := config.SetupSetting()
if err != nil {
log.Fatalf("init.setupSetting err: %v", err)
}
//其他逻辑
}
三,测试效果:
$ go run main.go
setting:
&{mysql dbusername dbpassword 127.0.0.1:3306 dbname utf8 true 10 30}