我一直在try 编写一个定制的UnmarshalYAML
函数,该函数将YAML解组为 struct ,并保持意外参数,将它们保存到映射到 struct 本身.
我试着写这个(https://go.dev/play/p/azf2hksriQ1),但是,当然,当我试图在UnmarshalYAML
中解组 struct 时,我会得到一个无限循环.
有没有人对如何使这个工作有任何建议? 非常感谢!
我一直在try 编写一个定制的UnmarshalYAML
函数,该函数将YAML解组为 struct ,并保持意外参数,将它们保存到映射到 struct 本身.
我试着写这个(https://go.dev/play/p/azf2hksriQ1),但是,当然,当我试图在UnmarshalYAML
中解组 struct 时,我会得到一个无限循环.
有没有人对如何使这个工作有任何建议? 非常感谢!
您可以使用一种简单的包装技术,为原始类型定义一个类型别名(这样yaml.Unmarshaler
就不会调用您的UmarshalYAML
方法),并创建一个嵌入所有已知和未知参数的 struct .
type Foo struct {
Param1 string `yaml:"param1"`
Param2 []int `yaml:"param2"`
// NOTE: we explicitly ignore this parameter so it won't be
// eventually unmarshaled
Extensions map[string]any `yaml:"-"`
}
// UnmarshalYAML implements the yaml.UnmarshalYAML interface.
func (f *Foo) UnmarshalYAML(value *yaml.Node) error {
// Here we are wrapping Foo, so it will be unmarshaled
// using without calling foo.UnmarshalYAML
type Wrapped Foo
// NOTE: for yaml it's required to provide inline
// option if we would like to embed
var val struct {
Wrapped `yaml:",inline"`
Extensions map[string]any `yaml:",inline"`
}
if err := value.Decode(&val); err != nil {
return err
}
*f = Foo(val.Wrapped)
f.Extensions = val.Extensions
return nil
}