This tutorial explains how to read and write yaml files in Golang.

There are multiple packages available for yaml serialization, This example covers an example on gopkg.in/yaml.v2

Let’s declare a sample yaml file

yaml is a superset of json. It contains key and value pairs with included indentation and tabs.

Given the yaml example file with database dictionary details.

--- # Application configuration - application.yaml
author: Franc
database:
  driver: com.mysql.jdbc.Driver
  port: 3306
  dbname: students
  username: root
  password: root
support:
  - mysql
  - mongodb
  - postgres

It contains

  • Contains Key database mapped with object
  • Contains array key of values

Next, In Terminal, Install package gopkg.in/yaml.v3 in a project.

~/read-write$ go get gopkg.in/yaml.v3
go: downloading gopkg.in/yaml.v3 v3.0.1
go: added gopkg.in/yaml.v3 v3.0.1

This package provides two methods yaml.unmarshal() Convert yaml file content into Golang struct yaml.marshal() Writes go struct into yaml file.

How to read YAML file in Golang

There are This example Parse/Read yaml file into an struct object in Golang

Create a struct object similar to format of yaml file. struct object contains

  • Plain keys author
  • Nested struct such as Database
  • One of the key contains an array of elements

Following steps to read the yaml file

  • First Define an struct with the same format of a yaml
  • Define an empty object of the struct
  • Read the yaml file using ioutil.ReadFile("config.yaml"), returns data, else err if any I/O Operation error.
  • Once data is in a variable, pass this to a yaml.Unmarshal(), which takes an empty struct, It does convert data into a struct in Golang
  • You can access the struct values in printf functions
package main

import (
  "fmt"
  "gopkg.in/yaml.v2"
  "io/ioutil"
)

type MyConfig struct {
        author string
        database struct {
          port     int
          dbname   string
          username string
          password string
        }
  support   []string
}

func main() {
  // Reading from a YAML file
  data, err := ioutil.ReadFile("config.yaml")
  if err != nil {
    fmt.Println("Error reading YAML file:", err)
    return
  }

  var config MyConfig;

  err = yaml.Unmarshal(data, &config);

  if err != nil {
    fmt.Println("Error unmarshalling YAML:", err)
    return
  }

fmt.Printf("%+v\n", config)
}

Struct type defined with all fields in yaml key and value types.

type MyConfig struct {
        author string
        database struct {
          port     int
          dbname   string
          username string
          password string
        }
  support   []string
}

How to Write struct object to YAML file

  • Define struct type with all fields in yaml
  • Initialize a Data with struct object in golang
  • use yaml.Marshal function to write struct to golang object data
  • ioutil.WriteFile writes the data to yaml file

Finally, Struct data is serialized into YAML format.

package main

import (
    "fmt"
    "gopkg.in/yaml.v2"
    "io/ioutil"
)
type MyConfig struct {
  author string
  database struct {
    port     int64
    dbname   string
    username string
    password string
    }
  support   []string
}
func main() {
    // Creating a Person struct
    config := MyConfig{
      author: "Franc",
      database: {
        driver:  "com.mysql.jdbc.Driver",
        port: "3306",
        dbname: "students",
        username: "root",
        password: "root",
      },
      support: {"mysql", "mongodb", "postgres" }
    }

    // Writing the Person struct to a YAML file
    data, err := yaml.Marshal(config)
    if err != nil {
        fmt.Println("Error marshalling to YAML:", err)
        return
    }

    err = ioutil.WriteFile("result.yaml", yamlData, 0644)
    if err != nil {
        fmt.Println("Error writing YAML file:", err)
    }
}

And the application1.yaml file created with the below content

author: Franc
database:
  driver: com.mysql.jdbc.Driver
  port: 3306
  dbname: students
  username: root
  password: root
support:
  - mysql
  - mongodb
  - postgres