How to Read and Write YAML in Go (gopkg.in/yaml.v3)

Use yaml.Marshal to write Go structs to YAML and yaml.Unmarshal to read YAML back into Go structs.

Use yaml.Marshal to convert Go structs to YAML bytes and yaml.Unmarshal to parse YAML bytes back into Go structs.

package main

import (
	"fmt"
	"gopkg.in/yaml.v3"
)

type Config struct {
	Name string `yaml:"name"`
	Port int    `yaml:"port"`
}

func main() {
	// Write YAML
	cfg := Config{Name: "server", Port: 8080}
	data, err := yaml.Marshal(&cfg)
	if err != nil {
		panic(err)
	}
	fmt.Println(string(data))

	// Read YAML
	var newCfg Config
	err = yaml.Unmarshal(data, &newCfg)
	if err != nil {
		panic(err)
	}
	fmt.Printf("%+v\n", newCfg)
}