What is the string after the name and type in a struct in Golang?

4/5/2019

I am looking at https://godoc.org/k8s.io/api/core/v1#Secret

type Secret struct {
    metav1.TypeMeta `json:",inline"`
    // Standard object's metadata.
    // More info: https://git.k8s.io/community/contributors/devel/api-conventions.md#metadata
    // +optional
    metav1.ObjectMeta `json:"metadata,omitempty" protobuf:"bytes,1,opt,name=metadata"`

    // Data contains the secret data. Each key must consist of alphanumeric
    // characters, '-', '_' or '.'. The serialized form of the secret data is a
    // base64 encoded string, representing the arbitrary (possibly non-string)
    // data value here. Described in https://tools.ietf.org/html/rfc4648#section-4
    // +optional
    Data map[string][]byte `json:"data,omitempty" protobuf:"bytes,2,rep,name=data"`

    // stringData allows specifying non-binary secret data in string form.
    // It is provided as a write-only convenience method.
    // All keys and values are merged into the data field on write, overwriting any existing values.
    // It is never output when reading from the API.
    // +k8s:conversion-gen=false
    // +optional
    StringData map[string]string `json:"stringData,omitempty" protobuf:"bytes,4,rep,name=stringData"`

    // Used to facilitate programmatic handling of secret data.
    // +optional
    Type SecretType `json:"type,omitempty" protobuf:"bytes,3,opt,name=type,casttype=SecretType"`
}

Take Data map[string][]byte `json:"data,omitempty" protobuf:"bytes,2,rep,name=data"` for example, I know Data is the name and map[string][]byte is the type, what is the third thing that follows? What does it do and when is it necessary to include this third thing?

-- mango
go
kubernetes-secrets
struct

1 Answer

4/5/2019

The json:"data,omitempty" protobuf:"bytes,2,rep,name=data" are called struct tags. Some useful links on the topic are:

  • The official language spec here
  • Some very well known ones here
  • A tutorial how to create custom ones here.

The tags are part of the struct's definition and allow you to tell the struct how to store data, create mappings, do validations, etc. In fact, you'll see lots of them in Go packages that handle data.

-- retgits
Source: StackOverflow