YAML in Go

From NovaOrdis Knowledge Base
Revision as of 00:20, 17 October 2023 by Ovidiu (talk | contribs) (→‎Overview)
Jump to navigation Jump to search

Internal

Overview

Declare a recursive structure that matches the structure of the YAML file, and then use a YAML encoder/decoder to marshall/unmarshall data in and out:

package main

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

//
// color: "blue:
// details:
//   size: 10
//   weight 2.2
//   used: true
//   options:
//     - light
//     - medium
//     - heavy
//

type Root struct {
	Color   string  `yaml:"color"`
	Details Details `yaml:"details"`
}

type Details struct {
	Size    int      `yaml:"size"`
	Weight  float64  `yaml:"weight"`
	Used    bool     `yaml:"used"`
	Options []string `yaml:"options"`
}

func main() {
	root := Root{
		Color: "blue",
		Details: Details{
			Size:    10,
			Weight:  2.2,
			Used:    true,
			Options: []string{"light", "medium", "heavy"},
		},
	}
	f, e := os.Create("/Users/ovidiu/tmp/test.yaml")
	if e != nil {
		panic(e)
	}
	//
	// Marshal recursive memory struct into a file
	//
	if e := yaml.NewEncoder(f).Encode(&root); e != nil {
		panic(e)
	}
	if e = f.Close(); e != nil {
		panic(e)
	}
	fmt.Printf("yaml file written and closed\n")

	f, e = os.Open("/Users/ovidiu/tmp/test.yaml")
	if e != nil {
		panic(e)
	}
	defer func() {
		if e = f.Close(); e != nil {
			fmt.Printf("failed to close the file\n")
		}
	}()
	//
	// Unmarshall the file into a different memory struct
	//
	config2 := Root{}
	if e = yaml.NewDecoder(f).Decode(&config2); e != nil {
		panic(e)
	}
	fmt.Printf("%+v\n", config2)
}