golang

Golang YAML

Yet Another Markup Language or YAML for short is a data-serialization with a heavy emphasis on human readability. It is often used as a configuration language for major tools and applications, debug logs, document headers, etc.

With its rise over the recent years, learning how to work with YAML files can be very beneficial. In this article, we will learn how to work with YAML file using the yaml.v3 package in Go.

Golang YAML Package

To work with YAML in Go, we use the Yaml.v3 package. It provides tools and methods to performing encoding and decoding of YAML data.

To install the package, run the go get command as:

go get gopkg.in/yaml.v3

Once installed, you can import the package as shown:

import "gopkg.in/yaml.v3"

Golang Read YAML

Let us begin by discussing how to read YAML files in Go. Suppose we have a sample YAML file as shown below:

item1: 100

item2: 40

item3: 22

item4: 50

item5: 323

We can use the YAML file using the Unmarshal method. An example code is as shown below:

package main
import (
    "fmt"
    "io/ioutil"
    "log"

    "gopkg.in/yaml.v3"
)

funcmain() {
    file, err := ioutil.ReadFile("users.yaml")
    if err != nil {
        log.Fatal(err)
    }
    data := make(map[interface{}]interface{})
    error := yaml.Unmarshal([]byte(file), &data)
    if error != nil {
        log.Fatal(err)
    }
    for key, value := range data {
        fmt.Printf("%s : %d\n", key, value)
    }
}

In the example code above, we read the file using the ioutil.ReadFile() method. We then create a map to store the data of type interface, interface.

We then Unmarshal the data from the file using the using the Unmarshal method. Finally, we iterate over the keys and values of the map using the range operator.

The code above should return:

item1 : 100

item2 : 40

item3 : 22

item4 : 50

item5 : 323

Suppose you have a nested YAML file as shown:

dev1:
    name: John Creese
    department: Game developer
dev2:
  name: Emma Rin
  department: DevOps Developer
dev3:
  name: SammuelMwese
  department: Backe-End Developer

For that, we can use the structure to store the information as shown:

type User struct {
    Name       string
    Department string
}

Next, we can perform a simple Unmarshal operation as:

package main

import (
    "fmt"
    "io/ioutil"
    "log"

    "gopkg.in/yaml.v3"
)

type User struct {
    Name       string
    Department string
}

funcmain() {
    file, err := ioutil.ReadFile("users.yaml")
    if err != nil {
        log.Fatal(err)
    }
    data := make(map[string]User)
    err1 := yaml.Unmarshal(file, &data)
    if err1 != nil {
        log.Fatal(err1)
    }
    for key, value := range data {
        fmt.Println(key, value)
    }
}

The code above should return an output as:

dev1 {John Creese Game developer}

dev2 {Emma Rin DevOps Developer}

dev3 {Sammuel Mwese Backe-End Developer}

Golang Write YAML

To write YAML file, we can use the marshal method. An example is as shown below:

package main
import (
    "fmt"
    "io/ioutil"
    "log"

    "gopkg.in/yaml.v3"
)
funcmain() {
fruits := [...]string{"apple", "orange", "mango", "strawberry"}
data, err := yaml.Marshal(fruits)
if err != nil {
    log.Fatal(err)
}
err1 := ioutil.WriteFile("fruits.yaml", data, 0644)
if err1 != nil {
    log.Fatal(err1)
}
fmt.Println("Success!")
}

In the example above, we use the marshal method to serialize the slice of strings into YAML. We then use the serialized data and write it into a file.

If the file does not exist, the code should create it with the specified permission and write to it. Running the above program should return:

$ go run main.go

Success!

Closing

This tutorial covered the basics of reading and writing YAML Files in Go using the Yaml.v3 package. Check the docs to learn more.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list