要解析yml文件,首先需要知道yml文件語法格式,可以參考博客:
https://blog.csdn.net/csdniter/article/details/103313432
解析yml文件和解析json數據方法一樣,使用的是github上第三方開源gopkg.in/yaml.v2
第一步:新建一個yaml文件,比如conf.yaml
host: localhost:3306
user: root
pwd: 123456
dbname: test
devs:
- 10.37.51.2:20008
- 10.37.51.3:20008
filter_types:
813-http: 0
第二步:新建一個go文件,進行解析
package main
import (
"io/ioutil"
"gopkg.in/yaml.v2"
"fmt"
)
func main() {
var c conf
conf:=c.getConf()
fmt.Println(conf.Host)
fmt.Println(conf.Devs[0])
fmt.Println(conf.FilterTypes.813-http )
}
//profile variables
type conf struct {
Host string `yaml:"host"`
User string `yaml:"user"`
Pwd string `yaml:"pwd"`
Dbname string `yaml:"dbname"`
Devs []string `yaml:"devs"`
FilterTypes map[string]int `yaml:"filter_types"`
}
func (c *conf) getConf() *conf {
yamlFile, err := ioutil.ReadFile("conf.yaml")
if err != nil {
fmt.Println(err.Error())
}
err = yaml.Unmarshal(yamlFile, c)
if err != nil {
fmt.Println(err.Error())
}
return c
}