解组 yaml,同时保留额外参数

问题描述 投票:0回答:1

我一直在尝试编写一个自定义

UnmarshalYAML
函数,它将将 yaml 解组为结构,并保留意外的参数,将它们保存到结构本身的映射中。

我尝试编写这个(https://go.dev/play/p/azf2hksriQ1),但是,当然,当我尝试解组

UnmarshalYAML
内部的结构时,我遇到了无限循环。

有人对如何进行这项工作有任何建议吗? 非常感谢!

go yaml unmarshalling
1个回答
0
投票

用解组器类型包装您的类型,然后对包装的值调用

Decode


type Foo struct {
    Param1     string         `yaml:"param1"`
    Param2     []int          `yaml:"param2"`
    Extensions map[string]any `yaml:"extensions"`
}

type FooUnmarshaler struct {
    Foo
}

// UnmarshalYAML implements the yaml.UnmarshalYAML interface.
func (f *FooUnmarshaler) UnmarshalYAML(value *yaml.Node) error {
    // ... snip ...

    // call Decode on the contained value, which will use default decoding
    if err = value.Decode(&f.Foo); err == nil {
        return nil
    }

    // ... snip ...
}

func main() {
    // ... snip ...

    // user your unmarshaler type
    foo := FooUnmarshaler{}

    err := yaml.Unmarshal([]byte(y), &foo)
    if err != nil {
        panic(fmt.Errorf("Error unmarshaling: %v", err))
    }

    // access the actual data via foo.Foo
    spew.Dump(foo.Foo)
}

游乐场链接,输出:

(main.Foo) {
 Param1: (string) (len=4) "test",
 Param2: ([]int) (len=3 cap=3) {
  (int) 2,
  (int) 4,
  (int) 6
 },
 Extensions: (map[string]interface {}) (len=1) {
  (string) (len=5) "x-foo": (string) (len=3) "bar"
 }
}
© www.soinside.com 2019 - 2024. All rights reserved.