1. 程式人生 > 程式設計 >golang解析yaml檔案操作

golang解析yaml檔案操作

首先安裝解析的第三方包:

go get gopkg.in/yaml.v2

示例:

package main 
import (
 "os"
 "log"
 "fmt"
 "encoding/json" 
 "gopkg.in/yaml.v2"
)
 
type Config struct {
 Test Test `yaml:"test"`
}
 
type Test struct {
 User []string `yaml:"user"`
 MQTT MQ `yaml:"mqtt"`
 Http HTTP `yaml:"http"`
}
 
type HTTP struct {
 Port string `yaml:"port"`
 Host string `yaml:"host"`
} 
 
type MQ struct {
 Host string `yaml:"host"`
 Username string `yaml:"username"`
 Password string `yaml:"password"`
} 
 
//read yaml config
//注:path為yaml或yml檔案的路徑
func ReadYamlConfig(path string) (*Config,error){
 conf := &Config{}
 if f,err := os.Open(path); err != nil {
  return nil,err
 } else {
 yaml.NewDecoder(f).Decode(conf)
 }
 return conf,nil
}
 
//test yaml
func main() {
 conf,err := ReadYamlConfig("D:/test_yaml/test.yaml")
 if err != nil {
 log.Fatal(err)
 }
 
 byts,err := json.Marshal(conf)
 if err != nil {
 log.Fatal(err)
 }
 
 fmt.Println(string(byts))
}
 

test.yaml內容如下:

test:
 user:
 - Tom
 - Lily
 - Skay
 
 mqtt:
  host: localhost:1883
  username: test
  password: test
 
 http: {port: "8080",host: "127.0.0.1"}

執行結果:

{"Test":{"User":["Tom","Lily","Skay"],"MQTT":{"Host":"localhost:1883","Username":"test","Password":"test"},"Http":{"Port":"8080","Host":"127.0.0.1"}}}

補充:golang 讀取yml格式,多結構體級聯

1.安裝yml解析包

進入到gopath下執行命令

go get gopkg.in/yaml.v2

原始碼地址https://github.com/go-yaml/yaml

2.設定配置檔案config.yml

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

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.配置檔案中字母要小寫,結構體屬性首字母要大寫,開發比較快

也可以指定如:yaml:"c",只不過有點麻煩,當然如果重新命名必須要指定

2.yaml:",flow"

這個意思是將陣列用[“a”,”b”]這樣的格式展示,預設展示形式是

- a

- b

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援我們。如有錯誤或未考慮完全的地方,望不吝賜教。