1 回答
TA贡献2065条经验 获得超13个赞
没有官方的 yaml 库,但是gopkg.in/yaml.v2是一个不错的选择。要解组给定的 yaml,您可以定义结构并将 yaml 标签添加到属性中。
通过为网桥和 vlan 使用映射并为端口使用数组,您可以毫无问题地解组数据。
当您使用地图时,请记住迭代地图并不能保证返回元素的顺序。
该程序将解组您给定的结构:
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 关注
- 86 浏览
添加回答
举报