SoFunction
Updated on 2025-03-03

Tutorial on using Golang tool library viper

viperyesgoThe library used in the project to read configuration files, supports readingyamltomljsonhclenvConfiguration files in other formats

Read environment variables

viperCan read the terminal's environment variables

If you're usingzshexist~/.zshrcSet in, ifbashexist~/.bashrcSettings in

When writing environment variables, there cannot be spaces on both sides of the equal sign, otherwise an error will be reported.

export APP_DEBUG=true

After writing it, remembersourceOnce, or restart the terminal

source ~/.zshrc

useRead all environment variables tovipermiddle

Then it can be used("APP_DEBUG")Get environment variables

func GetEnvInfo(env string) bool {
	()
	return (env)
}
app_debug := GetEnvInfo("APP_DEBUG")
(app_debug) // true

Read local configuration files

Create a new oneThe file, the content is as follows:

host: "127.0.0.1"
port: 50051

Then useviperRead,setConfigFileThe path to be filled in is relative toThe path

useTo read the configuration file

("./")
if err := (); err != nil {
  panic(err)
}
(("host")) // "127.0.0.1"

useTo set the file name,To set the file type, you can read configuration files more flexibly

  • Set file name without suffix
  • Set file type
  • Set file path
("config-debug")
("yaml")
("./")
if err := (); err != nil {
  panic(err)
}
(("host")) // "127.0.0.1"

Map configurations in configuration files into structures

Each timeTo obtain the configuration in the configuration file, you will write a lot of duplicate code, and you can map the configuration in the configuration file to the structure.

Create a new structure. The field name of the structure must be consistent with the field name in the configuration file.mapstructureTags to map

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

useMap configurations in configuration files into structures

var server Server
("config-debug")
("yaml")
("./")
if err := (); err != nil {
  panic(err)
}
if err := (&server); err != nil {
	panic(err)
}
() // "127.0.0.1"

Listen to changes in configuration information

If the configuration file changes,viperSupports monitoring of configuration file changes at runtime

useTo listen for changes in configuration files, useTo listen for changes in configuration files

onConfigChangeThe passed parameter is a function, and the parameter of the function is, reread the configuration file in the function, and then map the configuration in the configuration file to the structure

(func(e ) {
  _ = ()
  _ = (&server)
})
()

This is the end of this article about using the Golang tool library viper. For more related Golang viper content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!