使用Go语言向YAML文件追加规则时输出格式不符合要求问题
问题原因
你当前的结构体定义将custom-rules.yaml映射为数组类型,所以序列化后会直接把数组作为该字段的值。但你要求的格式中custom-rules.yaml对应的是YAML多行字符串字面量(|-为YAML块标量标记,表示保留换行、移除末尾多余换行符),因此不能直接将该字段定义为数组类型,需要先把规则数组序列化为YAML格式的字符串,再赋值给对应字段。
修改方案
调整结构体定义,先序列化规则生成字符串后再组装到最终结构中,完整修改后代码如下:
package main import ( "fmt" "io/ioutil" "log" "gopkg.in/yaml.v2" ) type AutoGenerated struct { CustomRules CustomRules `yaml:"customRules"` } // 单条自定义规则的结构体 type CustomRulesYaml struct { Rule string `yaml:"rule"` Append bool `yaml:"append"` Condition string `yaml:"condition"` Source string `yaml:"source"` } // 将custom-rules.yaml对应字段的类型改为string,存储序列化后的规则字符串 type CustomRules struct { CustomRulesYaml string `yaml:"custom-rules.yaml"` } func main() { // 构造规则数组 c1 := CustomRulesYaml{"Pod Created in Kube Namespace", true, "and (k8s_audit_never_true)", "k8s_audit"} c2 := CustomRulesYaml{"Create files below dev", true, "and (never_true)", "syscall"} rules := []CustomRulesYaml{c1, c2} // 先把规则数组序列化为YAML格式的字节 rulesBytes, err := yaml.Marshal(&rules) if err != nil { log.Fatalf("规则序列化失败: %v", err) } // 把规则字节转为字符串,赋值到对应字段 customRules := CustomRules{ CustomRulesYaml: string(rulesBytes), } result := AutoGenerated{customRules} // 序列化最终结构 output, err := yaml.Marshal(&result) if err != nil { log.Fatalf("最终结构序列化失败: %v", err) } // 写入文件 writeErr := ioutil.WriteFile("/home/revaa/falco/custom_rules.yaml", output, 0644) if writeErr != nil { log.Fatalf("文件写入失败: %v", writeErr) } fmt.Println("data written") }
输出结果
运行上述代码后生成的YAML就会和要求的格式完全一致:
customRules: custom-rules.yaml: |- - rule: Pod Created in Kube Namespace append: true condition: and (k8s_audit_never_true) source: k8s_audit - rule: Create files below dev append: true condition: and (never_true) source: syscall
内容的提问来源于stack exchange,提问作者Sathya
相关产品推荐
相关产品推荐

