🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
[TOC] ### 读取整个yaml配置文件 ***** #### 设计ymal文件和struct 一个`.ymal`文件: ``` ## Balancing name: "hash" host: host1: ip: "192.168.0.106" port: 6661 role: master host2: ip: "192.168.0.106" port: 6662 role: slave host3: ip: "192.168.0.106" port: 6663 role: slave ``` 设计数据结构 struct ``` type NodeServer struct { Address string `yaml:"address"` Ip string `yaml:"ip"` Port int `yaml:"port"` Role string `yaml:"role"` status bool `default:true` } type ConfServer struct { ReverseProxy map[string]*NodeServer `yaml:"host"` BalanceName string `yaml:"name"` } ``` #### 从ymal文件中获取配置 ``` func (c *ConfServer) GetConf(fileName string) *ConfServer { yamlFile, err := ioutil.ReadFile(fileName) if nil != err { fmt.Errorf("%v", err) return nil } err = yaml.UnmarshalStrict(yamlFile, c) if err != nil { fmt.Println(err.Error()) } return c } ``` #### 单元测试 ``` func TestConfServer_GetConf(t *testing.T) { var c ConfServer conf := c.GetConf("../conf/conf.yaml") if conf == nil { fmt.Print("conf is nil") return } data, err := json.Marshal(conf) if err != nil { fmt.Println("err:\t", err.Error()) return } fmt.Println("data:\t", string(data)) } ``` ### 读取yaml配置文件中的某一个属性 ``` ```