【问题标题】:Unable to unmarshal array field in golang无法在 golang 中解组数组字段
【发布时间】:2020-08-22 21:22:24
【问题描述】:

我正在尝试解组以下 flux HelmRelease 文件。

apiVersion: helm.fluxcd.io/v1
kind: HelmRelease
metadata:
  annotations:
    fluxcd.io/automated: 'false'
    fluxcd.io/tag.ats: glob:*
  name: ats
  namespace: myns
spec:
  chart:
    git: git@github.com:reponame/project.git
    path: charts/path1/path1/myapp
    ref: master
  releaseName: foobar
  values:
    allowAllEgress: true
    recycleApp: true
    hooks:
      slackChannel: https://hooks.slack.com/services/something/somethingelse/

这是我的模型

type HelmReleaseValues struct {
    AllowAllEgress bool `yaml:"allowAllEgress"`
    RecycleApp     bool `yaml:"recycleApp"`
    Hooks          `yaml:"hooks"`
}

type Hooks struct {
    SlackChannel string `yaml:"slackChannel"`
}

type Values struct {
    HelmReleaseValues `yaml:"values"`
    ReleaseName       string `yaml:"releaseName"`
    Chart             `yaml:"chart"`
}

type Spec struct {
    Values `yaml:"spec"`
}

问题是allowAllEgressrecycleApp 字段正在被解组。

但是,我的结构中的 Hooks 字段结果是空的。

我在结构建模/标记中做错了什么?

编辑:这是我的代码

package main

import (
    "fmt"
    "io/ioutil"
    "os"

    "github.com/davecgh/go-spew/spew"
    "gopkg.in/yaml.v3"
)

const ExitCodeCmdErr = 1

func main() {
    rawYaml := parseHelmReleaseFile("myfile.yaml")
    spew.Dump(rawYaml)
}

func parseHelmReleaseFile(fileName string) Spec {

    var v Spec

    yamlFile, err := ioutil.ReadFile(fileName)
    if err != nil {
        fmt.Printf("yaml file err   #%v ", err)
        os.Exit(ExitCodeCmdErr)
    }

    err = yaml.Unmarshal(yamlFile, &v)
    if err != nil {
        fmt.Printf("Unmarshal: %v", err)
        os.Exit(ExitCodeCmdErr)
    }

    return v
}

我正在运行程序并搜索输出(实际的 helm 发布文件很大)

▶ go clean && gb .             
~/Desktop/yamltutorial
./foobar | grep -i hooks -A 3
--
   Hooks: (main.Hooks) {
    SlackChannel: (string) ""
   }
  },

【问题讨论】:

  • 你能分享实际重现问题的代码吗?因为你在那里的东西似乎工作得很好:play.golang.org/p/ExF4tWirDKB
  • 谢谢,检查我的更新

标签: go struct yaml unmarshalling


【解决方案1】:

你没有图表结构

type Chart struct {
    Git  string `yaml:"git"`
    Path string `yaml:"path"`
    Ref  string `yaml:"ref"`
}

添加并得到以下输出

{Values:{HelmReleaseValues:{AllowAllEgress:true RecycleApp:true Hooks:{SlackChannel:https://hooks.slack.com/services/something/somethingelse/}} ReleaseName:foobar Chart:{Git:git@github.com:reponame/project.git Path:charts/path1/path1/myapp Ref:master}}}

包含完整代码的 Playground 文件。

https://play.golang.org/p/vCnjApr6gI9

【讨论】:

    猜你喜欢
    • 2020-07-19
    • 2018-03-24
    • 2021-09-22
    • 1970-01-01
    • 1970-01-01
    • 2016-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多