SoFunction
Updated on 2025-03-05

Golang Practice Records Reading Yaml Configuration Files

This article parses the yaml file.

download

yaml executiongo get /spf13/viperInstall.

golang has many libraries that can explain yaml files. This article uses viper for analysis and executiongo get /spf13/viperInstall.

yaml syntax rules

  • Yaml is case sensitive.
  • The hierarchical relationship of yaml can only be used to indent spaces, and the number of spaces indented in the same layer is the same, and the number is not important. Tab key is not allowed.
  • use#Comment, withshellSame.

Data Type

YAML supports the following commonly used data types:

  • Object: a collection of key-value pairs, also known as mapping/hashes/dictionary
  • Array: a set of values ​​arranged in order, also known as sequence / list
  • Scalars: single, non-redividable value

test

yaml configuration file

# yaml test sample# null or NULL is a keyword and cannot be written
# Several values ​​indicating that bool is true or falseresult_true: 
  - y
  - Y
  - yes
  - Yes
  - YES
  - true
  - True
  - TRUE
  - on
  - On
  - ON

# Another form of arrayresult_false: [n, N, no, No, NO , false, False, FALSE , off, Off, OFF]

# Name# stringname: conf file

# Version# If pressing floating point, 2.0 will be converted to 2# If pressing a string, leave it as it isversion: 2.0

# Boolean class, convert to 1 or 0need: true

# timetime: 2020-10-03T09:21:13

empty: nul

#Object# Adding double quotes will escape \n, which means a line breakmy:
  name: late \n lee
  name1: "late \n lee"
  age: 99
  
# piecetext: |
  hello
  world!

# arrayfruit:
  - apple
  - apple1
  - apple2
  - apple3
  - apple4
  - apple5

# Multi-level arraymulti:
  sta:
    - 110 210 ddd 99
    - 133 135 1 2 1588 1509
    - 310-410
    - 333-444

# Multi-levelloginfo:
  log:
    dir: log

# Multi-level objectmymap:
  dir: "mymap"
  map_data:
    - name: "Online"
      attri: "Online Electronics"
      url: ""
    - name: "Offline"
      attri: "Offline电子"
      url: ""
    # more

This example basically covers most of the yaml formats. Including: strings, values, arrays, and multi-level maps.

Test code

The test code is as follows:

package test

import (
	"fmt"
	"os"
	"testing"

	"/spf13/viper"
)

var (
	cfgFile string
)

type mapUrl_t struct {
	Name  string `json:"name"`
	Attri string `json:"attri"`
	Url   string `json:"url"`
}

func TestYaml(t *) {
	("test of yaml...")

	// 2 ways to set configuration files	if cfgFile != "" {
		// Use config file from the flag.
		(cfgFile)
	} else {
		("./")
		("config")
		("yaml")
	}

	() // read in environment variables that match

	// Read	err := ()
	if err != nil {
		("'' file read error:", err)
		(0)
	}

	name := ("name") // Read string	version := ("version")

	need := ("need") // Read Boolean	theTime := ("time")
	empty := ("empty")
	text := ("text")

	("need: %v name: %v\nversion: %v \ntime: %v \nempty: %s \ntext: %v\n", need, name, version, theTime, empty, text)

	// Multi-level reading	name = ("")
	name1 := ("my.name1")
	age := ("")
	("name: %v, name1: %v age: %v \n", name, name1, age)

	// String array	newSta := ("")
	for idx, value := range newSta {
		("sta[%d]: %v\n", idx, value)
	}

	fruit := ("fruit")
	("fruit: %v\n", fruit)

	// Read non-existent fields, the string is empty, and the value is 0	bad := ("bad")
	bad1 := ("")
	("bad: [%v] bad1: [%v]\n", bad, bad1)

	// Read on, off and other values ​​according to values ​​and strings	result := ("result_true")
	("result true: [%v]\n", result)
	result1 := ("result_true")
	("result1 true: [%v]\n", result1)

	result = ("result_false")
	("result false: [%v]\n", result)
	result1 = ("result_false")
	("result1 false: [%v]\n", result1)

	logdir := ("")
	("logdir: %v\n", logdir)

	// Multi-level object	// tmpMap := make([]mapUrl_t, 0, 20)
	var tmpMap []mapUrl_t

	("mymap.map_data", &tmpMap)

	for _, item := range tmpMap {
		("name: %v url: %v\n", , )
	}
}

Test command:

go test -v -run TestYaml

Test results:

test of yaml...
need: true name: conf file
version: 2
time: 2020-10-03T09:21:13
empty: nul
text: hello
world!

name: late \n lee, name1: late
 lee age: 99
sta[0]: 110 210 ddd 99
sta[1]: 133 135 1 2 1588 1509
sta[2]: 310-410
sta[3]: 333-444
fruit: [apple apple1 apple2 apple3 apple4 apple5]
bad: [] bad1: [0]
result true: [[1 1 1 1 1 1 1 1 1 1 1]]
result1 true: [[true true true true true true true true true true true]]
result false: [[0 0 0 0 0 0 0 0 0 0 0]]
result1 false: [[false false false false false false false false false false false]]
logdir: log
name: Online url: 
name: Offline url: 

Results Description

1、name: "late \n lee"The output will be line-breaked. andname: late \n leeThen it will be output as it is.
2. The value of the parameter cannot be null or NULL, but it can be nul. If null, the parsed value is empty.
3. If the field does not exist, there will be no error. The value obtained by parsing according to the string is empty. If you use a numeric value, the value will be 0.

4. ExpressfalseThe keywords aren, N, no, No, NO , false, False, FALSE , off, Off, OFF, expresstrueThere isy, Y, yes, Yes, YES, true, True, TRUE, on, On, ON. Pay attention when using it.

5. For multi-level objects, you can use it, the usage is similar to parsing json.

Summarize

This is the article about reading yaml configuration files in Golang practice transcripts. For more information about reading yaml configuration files, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!