多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
[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配置文件中的某一个属性 ``` ```