如何使用 YAML 编组 golang 嵌套结构

我如何表示此结构的匹配标签部分以打印出来。我尝试以类似元数据的格式添加“NetworkPolicySpecPodSelector”结构,但我的格式不正确。


package main


import (

    "fmt"

    "io/ioutil"


    "gopkg.in/yaml.v2"

)


type Metadata struct {

    Name      string `yaml:"name"`

    Namespace string `yaml:"namespace"`

}


type Spec struct {

    PodSelector NetworkPolicySpecPodSelector `yaml:"Spec"`

}


type NetworkPolicySpecPodSelector struct {

    MatchLabels map[string][]string `yaml:"matchLabels"`

}


type Ingress struct {

}


type NetworkPolicy struct {

    ApiVersion string   `yaml:"apiVersion`

    Kind       string   `yaml:"kind"`

    Metadata   Metadata `yaml:"metadata"`

    Spec       struct {

        PodSelector NetworkPolicySpecPodSelector

    }

    PolicyTypes []string `yaml:"policyTypes"`

}


func main() {

    np := NetworkPolicy{

        ApiVersion: "networking.k8s.io/v1",

        Kind:       "NetworkPolicy",

        Metadata: Metadata{

            Name:      "allow-ingress",

            Namespace: "default",

        },

        PolicyTypes: []string{"Ingress"},

    }


    yamlData, err := yaml.Marshal(&np)


    if err != nil {

        fmt.Printf("Error while Marshaling. %v", err)

    }


    fileName := "test.yaml"

    err = ioutil.WriteFile(fileName, yamlData, 0644)

    if err != nil {

        panic("Unable to write data into the file")

    }

}

我的输出在这里:


apiversion: networking.k8s.io/v1

kind: NetworkPolicy

metadata:

  name: allow-ingress

  namespace: default

spec:

  podselector:

    matchLabels: {}

policyTypes:

- Ingress

期望的输出:


apiversion: networking.k8s.io/v1

kind: NetworkPolicy

metadata:

  name: allow-ingress

  namespace: default

spec:

  podselector:

    matchLabels: 

      env:prod

policyTypes:

- Ingress

仍然需要成长,但我在这方面苦苦挣扎。该项目的目标是使用 YAML 输出 Kubernetes 网络策略。


慕姐8265434
浏览 86回答 1
1回答

拉莫斯之舞

首先,您需要修复结构字段标签以反映您想要的结构。Spec在NetworkPolicy需要序列化为键spec及其字段PodSelector为podselector:type NetworkPolicy struct {    ApiVersion  string   `yaml:"apiVersion`    Kind        string   `yaml:"kind"`    Metadata    Metadata `yaml:"metadata"`    Spec        Spec     `yaml:"spec"`    PolicyTypes []string `yaml:"policyTypes"`}type Spec struct {    PodSelector NetworkPolicySpecPodSelector `yaml:"podselector"`}然后你可以简单地使用文字:    np := NetworkPolicy{        ApiVersion: "networking.k8s.io/v1",        Kind:       "NetworkPolicy",        Metadata: Metadata{            Name:      "allow-ingress",            Namespace: "default",        },        Spec: Spec{            PodSelector: NetworkPolicySpecPodSelector{                MatchLabels: map[string][]string{                    "env": []string{"prod"},                },            },        },        PolicyTypes: []string{"Ingress"},    }这是操场上的完整示例:https ://go.dev/play/p/xJ-mmCVcv2M注意:在您的代码片段中,类型MatchLabels是map[string][]string. 我保持这样,虽然从示例中看起来像你想要map[string]string的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go