skip to Main Content

I’m trying to read a yaml file via golang.

But the "matchLabels" sub-struct is not being recognized

yaml

apiVersion: apps/v1
kind: Deployment
metadata:
    name: nginx-deploy
    labels:
      app: test
spec:
    replicas: 3
    selector:
        matchLabels:
            app: web
    

struct

type myData struct {
    Apivesion string `yaml:"apiVersion"`
    Kind      string
    Metadata  struct {
        Name   string
        Labels struct {
            App string
        }
    }
    Spec struct {
        Replicas int64
        Selector struct {
            Matchlabels struct {
                App string
            }
        }
    }
}

Expectation

&{apps/v1 Deployment {nginx-deploy {test}} {3 {{web}}}}

Result

&{apps/v1 Deployment {nginx-deploy {test}} {3 {{}}}}

Fix didn’t work:

Matchlabels struct `yaml:"matchLabels"` {

3

Answers


  1. Chosen as BEST ANSWER

    Cerise Limón gave the answer in a comment:

    Field tags follow the type:

    Matchlabels struct { App string } 
    `yaml:"matchLabels"`
    

  2. I don’t think you implemented the suggested answer correctly, see where the tag is:

    type myData struct {
        Apivesion string `yaml:"apiVersion"`
        Kind      string
        Metadata  struct {
            Name   string
            Labels struct {
                App string
            }
        }
        Spec struct {
            Replicas int64
            Selector struct {
                Matchlabels struct {
                    App string
                } `yaml:"matchLabels"`
            }
        }
    }
    

    See also: https://go.dev/play/p/yd9c-iBz2yL

    Login or Signup to reply.
  3. type AutoGenerated struct {
        APIVersion string `yaml:"apiVersion"`
        Kind       string `yaml:"kind"`
        Metadata   struct {
            Name   string `yaml:"name"`
            Labels struct {
                App string `yaml:"app"`
            } `yaml:"labels"`
        } `yaml:"metadata"`
        Spec struct {
            Replicas int `yaml:"replicas"`
            Selector struct {
                MatchLabels struct {
                    App string `yaml:"app"`
                } `yaml:"matchLabels"`
            } `yaml:"selector"`
        } `yaml:"spec"`
    }
    

    You can use this tool, it is really helpful:

    https://zhwt.github.io/yaml-to-go/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search