1 回答

TA貢獻(xiàn)2065條經(jīng)驗(yàn) 獲得超14個(gè)贊
沒有官方的 yaml 庫(kù),但是gopkg.in/yaml.v2是一個(gè)不錯(cuò)的選擇。要解組給定的 yaml,您可以定義結(jié)構(gòu)并將 yaml 標(biāo)簽添加到屬性中。
通過(guò)為網(wǎng)橋和 vlan 使用映射并為端口使用數(shù)組,您可以毫無(wú)問(wèn)題地解組數(shù)據(jù)。
當(dāng)您使用地圖時(shí),請(qǐng)記住迭代地圖并不能保證返回元素的順序。
該程序?qū)⒔饨M您給定的結(jié)構(gòu):
package main
import (
"fmt"
"log"
yaml "gopkg.in/yaml.v2"
)
var data = `
controlling_bridge_1:
ip: "1.1.1.1"
ports: ["1","2"]
vlans:
vlan01:
name: "vlan1"
tag: 1001
ports: ["1"]
ip: "2.2.2.2"
vlan02:
name: "vlan02"
tag: 1002
ports: ["3", "4"]
ip: "3.3.3.1"
controlling_bridge_2:
ip: "1.1.1.1"
ports: ["1","2"]
vlans:
vlan01:
name: "vlan1"
tag: 1001
ports: ["1"]
ip: "2.2.2.2"
vlan02:
name: "vlan02"
tag: 1002
ports: ["3", "4"]
ip: "3.3.3.1"
`
type Bridge struct {
IP string `yaml:"ip"`
Ports []string `yaml:"ports"`
Vlans map[string]Vlan
}
type Vlan struct {
Name string `yaml:"name"`
Tag string `yaml:"tag"`
Ports []string `yaml:"ports"`
IP string `yaml:"ip"`
}
func main() {
bridges := map[string]Bridge{}
err := yaml.Unmarshal([]byte(data), &bridges)
if err != nil {
log.Fatalf("error: %v", err)
}
fmt.Printf("%+v\n", bridges)
}
- 1 回答
- 0 關(guān)注
- 129 瀏覽
添加回答
舉報(bào)