SoFunction
Updated on 2025-03-03

Implementation of golang's method to read yaml configuration file

Viper

Viper is a complete configuration solution for Go applications. It is designed to work in applications and can handle all types of configuration requirements and formats. It supports the following features:

  • Set default values
  • Read configuration information from configuration files in JSON, TOML, YAML, HCL, envfile, and Java properties formats
  • Real-time monitoring and rereading configuration files (optional)
  • Read from environment variable
  • Read and monitor configuration changes from remote configuration system (etcd or Consul)
  • Read configuration from command line parameters
  • Read configuration from buffer
  • Explicit configuration values

Install

go get /spf13/viper

use

Create a config folder in the project root directory, create it in the folder

servername: 'myserver'

mysql:
  name: 'mysql'

Read the configuration file information

package main

import (
	"log"

	"/spf13/viper"
)

func main() {
	v := ()

	// Set file name	("./config/")

	if err := (); err != nil {
		("Read configuration file failed")
	}

	servername := ("servername")
	mysql := ("")
	(servername, mysql)
}

Mapping yaml using structure

Modify the configuration file

name: 'Service Name'
port: 8080

use

package main

import (
	"log"

	"/spf13/viper"
)

type ServerConfig struct {
	Name string `mapstructure:"name"`
	Port int    `mapstructure:"port"`
}

func main() {

	cfg := ServerConfig{}
	v := ()

	// Set file name	("./config/")

	if err := (); err != nil {
		("Read configuration file failed")
	}

	if err := (&cfg); err != nil {
		(err)
	}

	(cfg)
}

Output

{Service name 8080}

Structure nested read configuration

Configuration File

name: 'Service Name'
port: 8080
mysql: 
  host: '127.0.0.1'
  port: 3306

Read configuration

package main

import (
	"log"

	"/spf13/viper"
)

type ServerConfig struct {
	Name        string      `mapstructure:"name"`
	Port        int         `mapstructure:"port"`
	MysqlConfig MysqlConfig `mapstructure:"mysql"` // Nested configuration}

type MysqlConfig struct {
	Host string `mapstructure:"host"`
	Port int    `mapstructure:"port"`
}

func main() {

	cfg := ServerConfig{}
	v := ()

	// Set file name	("./config/")

	if err := (); err != nil {
		("Read configuration file failed")
	}

	if err := (&cfg); err != nil {
		(err)
	}

	(cfg)
}

Output

{Service name 8080 {127.0.0.1 3306}}

Read different configuration files according to different environments

In actual development work, there are generally different development environments that involve reading different configuration files

This will use golang's flag package

package main

import (
	"flag"
	"log"
)


func main() {

	env := ("env", "local", "Please enter local dev test prod in the running environment")
	()

	("The current environment is" + *env)

}

run

go run .\ -help

Output

-env string
Please enter local dev test prod (default "local") in the running environment

This way it works

go run .\ -env dev

Output

The current environment is dev

Use flag to read configuration files of different environments

Create a new config folder in the project directory

And create 4 configuration files

Among them

name: 'dev service name'
port: 8080
mysql: 
  host: '127.0.0.1'
  port: 3306

In

package main

import (
	"flag"
	"fmt"
	"log"

	"/spf13/viper"
)

type ServerConfig struct {
	Name        string      `mapstructure:"name"`
	Port        int         `mapstructure:"port"`
	MysqlConfig MysqlConfig `mapstructure:"mysql"` // Nested configuration}

type MysqlConfig struct {
	Host string `mapstructure:"host"`
	Port int    `mapstructure:"port"`
}

func main() {

	env := ("env", "local", "Please enter local dev test prod in the running environment")
	()

	("The current environment is" + *env)

	cfg := ServerConfig{}
	v := ()
	var path string = ("./config/%", *env)
	// Set file name	(path)

	if err := (); err != nil {
		("Read configuration file failed")
	}

	if err := (&cfg); err != nil {
		(err)
	}

	(cfg)
}

run

go run .\ -env dev

Output

The current environment is dev
{dev service name 8080 {127.0.0.1 3306}}

This is the article about the implementation of golang's method of reading yaml configuration files. For more related golang's content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!