golang 读取yml格式,多结构体级联
发布时间:2020-12-16 18:07:32 所属栏目:大数据 来源:网络整理
导读:1.安装yml解析包 进入到gopath下执行命令 go get gopkg. in /yaml.v2 源码地址https://github.com/go-yaml/yaml 2.设置配置文件config.yml ipport: 192.168.2.95:10000startsendtime: 2017-01-02 08:08:08sendmaxcountperday: 100devices:- devid: 123456789
1.安装yml解析包进入到gopath下执行命令 go get gopkg.in/yaml.v2
源码地址https://github.com/go-yaml/yaml 2.设置配置文件config.ymlipport: 192.168.2.95:10000
startsendtime: 2017-01-02 08:08:08
sendmaxcountperday: 100
devices:
- devid: 123456789 nodes:
- pkid: 0 bkid: 0
index: 0
minvalue: 0
maxvalue: 60
datatype: normal
- pkid: 0 bkid: 0
index: 0
datatype: boolean
- devid: 10001 nodes:
- pkid: 0 bkid: 1
index: 0
datatype: boolean
warnfrequency: 10
sendfrequency: 10
3.编写测试类package main
import (
"fmt"
"gopkg.in/yaml.v2"
"io/ioutil"
)
//配置文件中字母要小写,结构体属性首字母要大写
type Myconf struct {
Ipport string
StartSendTime string
SendMaxCountPerDay int
Devices []Device
WarnFrequency int
SendFrequency int
}
type Device struct {
DevId string
Nodes []Node
}
type Node struct {
PkId string
BkId string
Index string
MinValue float32
MaxValue float32
DataType string
}
func main() {
data,_ := ioutil.ReadFile("config.yml")
fmt.Println(string(data))
t := Myconf{}
//把yaml形式的字符串解析成struct类型
yaml.Unmarshal(data,&t)
fmt.Println("初始数据",t)
if(t.Ipport==""){
fmt.Println("配置文件设置错误")
return;
}
d,_ := yaml.Marshal(&t)
fmt.Println("看看 :",string(d))
}
4.注意1.配置文件中字母要小写,结构体属性首字母要大写,开发比较快 - a - b (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |