SoFunction
Updated on 2025-03-05

Simple way to use the viper package under golang

Simple use of viper package under golang

Viper is a complete Go application configuration solution designed to work in applications and can handle all types of configuration requirements and formats

Using viper is not complicated. Without generating an instance, viper uses the default instance to cache configuration information. If you don't want to do this, you can use the () method to generate your own instance and directly upload the code

package main
import (
	"bytes"
	"fmt"
	"/spf13/viper"
)
func main() {
	("ContentDir", "content")
	("LayoutDir", "layouts")
	("Taxonomies", map[string]string{"tag": "tags", "category": "categories"})
	/**
		 The default parameters will be set, that is, after each read the file, these parameters will be read into the cache of viper.
         And when writing files using the method provided by viper, they will also be written in. When using the Set method, the default value will be overwritten.
	 **/
	("config")  // Set the name of the file to be read here	("yaml")    // Here is the type of file to be read	(".")       // Here you set the folder path to read the file. You can set multiple paths, and you will find the file from these paths in turn.	("./test3") // The second alternative path to set	("./test")  // The last alternative path to be set	err := () // ReadInConfig is used to read the found configuration file	if err != nil {
		panic(("fatal error config file: %w", err)) // Return the failed information, which may be because the file does not exist, etc.	}
	("newconf", true) // Set new parameters, the above describes the difference between Set and SetDefault, and will not be repeated here	()
	()
	("./test2/")
	("./test2/")
	/**
		 WriteConfig is used to write configuration information into a new configuration file. The name and suffix of the new file are set using SetConfigName("config") set on lines 20 and 21.
		 and ("yaml").  WriteConfigAs can specify the path to the new configuration file (path with file name).
		 WriteConfig writes the first AddConfigPath you define, that is, line 22: "(".") "
		 If the method name has Safe, it means that if the file already exists, an error will be reported.  Methods without Safe overwrite files when they already exist.
		 Here, the parameters set on lines 11, 12, 13 and 31 will be written to the new file together with the original parameters of the file.
	 **/
	var yamlExample = []byte(`
Hacker: true
name: steve
hobbies:
- skateboarding
- snowboarding
- go
clothing:
jacket: leather
trousers: denim
age: 35
eyes : brown
beard: true
`)
	("yaml")
	((yamlExample))
	x := ("name")
	y := ("name")
	(x)
	(y)
	/**
		 In addition to reading configuration information from a file, it can also be read from a byte stream. As shown above, the GetString method returns the value of the string type corresponding to the key.
		 Similarly, you can use GetInt, GetBool, etc., the Get method returns an interface, so it can be applied to all types.
	 **/
	("loud", "Verbose")
	("verbose", true)
	("loud", true)
	("loud")
	("verbose")
	/**
		 RegisterAlias ​​is used to register alias, which means that all your next operations about loud can be replaced by vervose.
		 But it is only a convenient alias for your program to run, and the configuration information it expresses does not contain the attribute verbose.
		 That is to say, when you finally write to the new configuration file, verbose will not appear
		 Last notice!  !  !  : In vaper, the key of the configuration information is case-insensitive, so the Verbose and verbose above are equivalent to
	 **/
    ()
	// Read environment variables	("CGO")
	/** Set environment variable prefix: CGO_, if it is cgo, it will automatically convert to uppercase.
		 This way, when using get to read environment variables, you can only read the configuration related to the project
	 **/
	((".", "_", "-", "_"))
	// Replace '.' and '-' in the (key) key string with '_',	// This allows other symbols to be used instead when using Get to get the value.	("ENABLED")                  // Bind "CGO_ENABLED" to "ENABLED"	("enabled")                  // Automatically convert to uppercase when matching environment variables, but the key is still lowercase	("-id", "GOROOT") // When two parameters are included, the prefix will not take effect	("PATH", "PATH")
	(("-id"))
	(("ENABLED"))
	(("enabled"))
	(("PATH"))
	// Viper is case sensitive when reading environment variables}

Interpretation of golang commonly used library viper

1. Introduction to viper

viper is a library for configuring solutions.

  • Supports various configuration files such as JSON, TOML, YAML, HCL, envfile and Java attribute configuration files
  • Supports monitoring file changes and rereading configurations
  • Supports reading configuration from environment variables
  • Supports reading configuration from remote configuration system (etcd or Consul) and can listen for remote configuration modifications
  • Supports reading configuration from the command line flag Flag, such as cobra

Viepr can be installed directly using the go get command

$ go get /spf13/viper

Use

//Load local configurationfunc InitInFromLocal() (*, error) {
	home := "./config"
	var v = ()
	//(err)
	("UserHomeDir", home)
	// Search config in home directory with name ".cobra" (without extension).
	(home)
	("toml")
	("pro")
	()
	if err := (); err == nil {
		("Using config file success:", ())
	} else {
		("Using config file:%s", err)
	}
	(("app_name_pro"))
	return v, nil
}
//Load the remote configurationfunc InitConfigFromRemote() error {
	// Remote configuration	("etcd", "http://127.0.0.1:2379", "config/")
	//("json")
	("")
	("yml")
	if err := (); err == nil {
		("use config file -> %s\n", ())
	} else {
		return err
	}
	return nil
}
//Set the default value	("email", "NAME HERE <EMAIL ADDRESS>")
	("license", "apache")
//Bind a single value cobra	("author", ().Lookup("author"))
	("useViper", ().Lookup("viper"))
//Bind multiple values	(())
//Get environment variable    ()
	(true)
	("CK")
// Listen to file changes// Listen to the callback after file changes(func(e ) {
  ("Config file changed:", )
  ((""))
})
()
//Write file from viper	("./")
	()
//Get subconfiguration items    ("db")

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.