go chapter 2 - read file(yaml)
func main() { data, err := ioutil.ReadFile("D:/test/widua.go") if err != nil { fmt.Println("read error") os.Exit(1) } fmt.Println(string(data)) }
------------------------------------------------------------------------------------------------------
config/app.yaml
ipport: 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
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)) }