程序模块中,缺少不了一些配置定义,这时定义yaml是个很好的选择
先定义yaml文件内容,文件名为:task_status_config.yaml
confs:#阅读类任务,即提醒任务read:name: readawait: #待开始任务status_id: 0ing: #进行中任务receipt: #是否已阅读yes:status_id: 4 #已完成no:status_id: 1 #进行中timeout: #已逾期receipt: #是否已阅读yes:status_id: 8 #已逾期-已完成no:status_id: 2 #已逾期-未完成#回执类任务,即预警任务receipt:name: receiptawait: #待开始任务status_id: 0ing: #进行中任务receipt: #是否已回执yes:status_id: 4 #已完成no:status_id: 1 #进行中timeout: #已逾期receipt: #是否已回执yes:status_id: 8 #已逾期-已完成no:status_id: 2 #已逾期-未完成#目标类任务,即系统任务target:name: targetawait: #待开始任务status_id: 0ing: #进行中任务receipt: #是否已回执yes:status_id: 3 #已回执no:status_id: 1 #进行中timeout: #已逾期receipt: #是否已回执yes:status_id: 7 #已逾期-已回执no:status_id: 2 #已逾期-未完成finish: #已完成任务status_id: 4 #已完成
编写程序读取yaml配置文件
package mainimport ("encoding/json""fmt""os""gopkg.in/yaml.v2"
)type TaskStatusConf struct {Confs map[string]*TaskClassify `yaml:"confs" json:"confs"`
}type TaskClassify struct {Name string `yaml:"name" json:"name"`Await StatusIdToInt `yaml:"await" json:"await"`Ing TaskRecept `yaml:"ing" json:"ing"`Timeout TaskRecept `yaml:"timeout" json:"timeout"`Finish StatusIdToInt `yaml:"finish" json:"finish"`
}type StatusIdToInt struct {StatusId int `yaml:"status_id" json:"status_id"`
}type TaskRecept struct {Receipt StatusReceipt `yaml:"receipt" json:"receipt"`
}type StatusReceipt struct {Yes StatusIdToInt `yaml:"yes" json:"yes"`No StatusIdToInt `yaml:"no" json:"no"`
}func getYaml() {var c TaskStatusConf//读取yaml配置文件, 将yaml配置文件,转换struct类型conf := c.getConf()//将对象,转换成json格式data, err := json.Marshal(conf)if err != nil {fmt.Println("err:\t", err.Error())return}//最终以json格式,输出fmt.Println("data(string):\t", string(data))var res TaskStatusConf_ = json.Unmarshal(data, &res)// 以结构体形式访问fmt.Println(res.Confs["read"].Ing.Receipt.No.StatusId)
}// 读取Yaml配置文件,
// 并转换成conf对象 struct结构
func (taskStatusConf *TaskStatusConf) getConf() *TaskStatusConf {//应该是 绝对地址yamlFile, err := os.ReadFile("../task_status_config.yaml")if err != nil {fmt.Println(err.Error())}//err = yaml.Unmarshal(yamlFile, kafkaCluster)err = yaml.UnmarshalStrict(yamlFile, taskStatusConf)if err != nil {fmt.Println(err.Error())}return taskStatusConf
}
运行结果: