Decoding and encoding

YAML is not included in the Go standard library but there are many third-party libraries available. The package that is more commonly used to handle this format is the go-yaml package (https://gopkg.in/yaml.v2).

It is built using the following standard encoding packages structure:

  • There are encoders and decoders.
  • There are Marshal/Unmarshal functions.
  • It allows struct tags.
  • The behavior of types can be customized by implementing the methods of the interfaces defined.

The interface is slightly different—the Unmarshaler receives the default marshaling function as arguments that can then be used with a data struct that is different to the type:

type Marshaler interface {
MarshalYAML() (interface{}, error)
}

type Unmarshaler interface {
UnmarshalYAML(unmarshal func(interface{}) error) error
}

We can use the struct tags in the same way as JSON tags:

type Character struct {
Name string `yaml:"name"`
Surname string `yaml:"surname"`
Job string `yaml:"job,omitempty"`
YearOfBirth int `yaml:"year_of_birth,omitempty"`
}

And we can use them to encode a data structure or, in this case, a list of structures:

var chars = []Character{{
Name: "William",
Surname: "Dyer",
Job: "professor",
YearOfBirth: 1875,
}, {
Surname: "Danforth",
Job: "student",
}}
e := yaml.NewEncoder(os.Stdout)
if err := e.Encode(chars); err != nil {
log.Fatalln(err)
}

Decoding works in the same way, as follows:

r := strings.NewReader(`- name: John Raymond
surname: Legrasse
job: policeman
- name: "Francis"
surname: Wayland Thurston
job: anthropologist`)
// define a new decoder
d := yaml.NewDecoder(r)
var c []Character
// decode the reader
if err := d.Decode(&c); err != nil {
log.Fatalln(err)
}
log.Printf("%+v", c)

We can see that all it takes to create Decoder is io.Reader and the receiving struct to execute the decode.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.23.147