首页 > 后端开发 > Golang > 正文

如何在 Go 中将 YAML 字段动态解析为特定结构?

Linda Hamilton
发布: 2024-10-28 12:58:30
原创
316 人浏览过

How to Dynamically Parse a YAML Field to Specific Structs in Go?

在 Go 中将 YAML 字段动态解析为特定结构

YAML 文件通常包含可以由多种类型的结构表示的字段。为了简化代码和 YAML 文件,请考虑以下 YAML 示例:

kind: "foo"
spec:
  fooVal: 4
登录后复制
kind: "bar"
spec:
  barVal: 5
登录后复制

用于解析的相应结构为:

<code class="go">type Spec struct {
    Kind string      `yaml:"kind"`
    Spec interface{} `yaml:"spec"`
}

type Foo struct {
    FooVal int `yaml:"fooVal"`
}

type Bar struct {
    BarVal int `yaml:"barVal"`
}</code>
登录后复制

当使用 map[string] 接口时{ Spec 字段的 } 是一个选项,对于较大的 YAML 文件,它可能会变得复杂。

使用自定义 Unmarshaler 的优雅解决方案

另一种方法涉及为以下对象创建自定义 Unmarshaler规格类型。要与 yaml.v2 一起使用,请实现以下内容:

<code class="go">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:"-"`
}</code>
登录后复制
<code class="go">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)
}</code>
登录后复制

对于 yaml.v3,请使用以下内容:

<code class="go">type Spec struct {
    Kind string      `yaml:"kind"`
    Spec interface{} `yaml:"-"`
}</code>
登录后复制
<code class="go">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)
}</code>
登录后复制

此解决方案动态映射 YAML根据“kind”字段将字段添加到适当的结构,从而无需额外的步骤或内存消耗。

以上是如何在 Go 中将 YAML 字段动态解析为特定结构?的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!