"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Dynamically Parse a YAML Field into a Finite Set of Structs in Go?

How to Dynamically Parse a YAML Field into a Finite Set of Structs in Go?

Published on 2024-11-08
Browse:619

How to Dynamically Parse a YAML Field into a Finite Set of Structs in Go?

Dynamically Parse YAML Field to a Finite Set of Structs in Go

Introduction

Parsing YAML into a struct in Go can be straightforward. However, when a YAML field can represent multiple possible structs, the task becomes more complex. This article explores a dynamic approach using Go's YAML package.

Dynamic Unmarshaling with YAML v2

For Yaml v2, the following approach can be used:

type yamlNode struct {
    unmarshal func(interface{}) error
}

func (n *yamlNode) UnmarshalYAML(unmarshal func(interface{}) error) error {
    n.unmarshal = unmarshal
    return nil
}

type Spec struct {
    Kind string      `yaml:"kind"`
    Spec interface{} `yaml:"-"
}
func (s *Spec) UnmarshalYAML(unmarshal func(interface{}) error) error {
    type S Spec
    type T struct {
        S `yaml:",inline"`
        Spec yamlNode `yaml:"spec"`
    }

    obj := &T{}
    if err := unmarshal(obj); err != nil {
        return err
    }
    *s = Spec(obj.S)

    switch s.Kind {
    case "foo":
        s.Spec = new(Foo)
    case "bar":
        s.Spec = new(Bar)
    default:
        panic("kind unknown")
    }
    return obj.Spec.unmarshal(s.Spec)
}

Dynamic Unmarshaling with YAML v3

For Yaml v3, the approach is slightly different:

type Spec struct {
    Kind string      `yaml:"kind"`
    Spec interface{} `yaml:"-"
}
func (s *Spec) UnmarshalYAML(n *yaml.Node) error {
    type S Spec
    type T struct {
        *S `yaml:",inline"`
        Spec yaml.Node `yaml:"spec"`
    }

    obj := &T{S: (*S)(s)}
    if err := n.Decode(obj); err != nil {
        return err
    }

    switch s.Kind {
    case "foo":
        s.Spec = new(Foo)
    case "bar":
        s.Spec = new(Bar)
    default:
        panic("kind unknown")
    }
    return obj.Spec.Decode(s.Spec)
}

Conclusion

These dynamic unmarshaling techniques allow for flexible parsing of YAML fields into a finite set of structs, providing a more elegant and efficient solution than the proposed workaround. Feel free to explore the provided code snippets and optimize the approach based on your specific requirements.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3