Introduction to Viper in Go and Golang


In Go, there are lots of packages to deal with utility configuration. The viper package deal is hottest amongst them in offering an entire configuration resolution of an utility. It helps quite a few configuration file codecs comparable to JSON, YAML, TOML, HCL and Java properties format. This programming tutorial introduces Golang’s viper package deal with Go code examples.

Seeking to be taught Go or Golang in an internet course atmosphere? We now have a listing of the Greatest On-line Programs to Study Go and Golang that will help you get began.

What’s the viper Library in Go and Golang?

As talked about, viper is a package deal that gives an entire configuration resolution in a Go challenge. Managing and sustaining configuration for an enormous and complex utility – comparable to constructing a server utility or every other utility which relies upon loads on person manipulation of configurations – is just not a simple job. Furthermore, trendy purposes are constructed to deploy in various kinds of environments, comparable to in Docker, cloud infrastructures, and so forth. In consequence, with a view to preserve consistency throughout deployment, purposes ought to be constructed to be open from little to excessive configurability. An exterior help that helps on this respect is just not solely a respite, but additionally very a lot welcome for the builders concerned in constructing such an answer.

The viper library, on this respect, can solely change the flag package deal, which gives provisions for growing UNIX methods, comparable to command line utilities. In line with the viper documentation, viper, other than being an entire configuration resolution for Go purposes, additionally helps 12-Issue apps. 12-Issue app is a strategy for constructing software-as-a-service (SAAS) purposes. Launched by Heroku, this method leverages portability, declarative codecs, and automation that makes purposes extra resilient to the adaptive wants of the altering atmosphere of software program deployment.

Learn: How one can Use the flag Bundle in Go

What Does the viper Library Assist in Go?

In line with the viper documentation, it helps the next in Go purposes:

  • Studying JSON, TOML, YAML, HCL, envfile and Java properties config information. Most configuration data of an utility is written on this format. Viper helps most of them.
  • Organising default configurations
  • Studying atmosphere variables
  • Studying distant configuration methods
  • Studying from command line flags
  • Studying from buffer
  • Setting express values

How one can Set up viper in Go

The steps to put in viper are much like putting in every other package deal in Go. As soon as a Go utility challenge has been arrange correctly with the required module file utilizing the go mod init command, a go.mod file might be created. This file maintains the record of packages used within the present challenge. Simply sort: go get github.com/spf13/viper to put in the viper package deal. Observe {that a} new record of packages associated to the viper package deal might be added within the go.mod file.

Go viper Code Instance

Suppose we need to get the values of the widespread Working System atmosphere variable known as PATH. Builders might achieve this utilizing the next Go code instance:

package deal important

import (
"fmt"
"github.com/spf13/viper"
)

func important() {
viper.BindEnv("PATH")
val := viper.Get("PATH")
fmt.Println("PATH:", val)
}

Observe that, within the operate important(), we used viper.BindEnv to bind a viper key to the atmosphere variable known as PATH. It’s case delicate, which means, as the secret’s supplied, it would use the atmosphere key that matches the important thing in uppercase if given in uppercase. Since, BindEnv can take multiple argument, every will signify atmosphere variable names that bind to this key and might be taken within the specified order.

The viper.Get operate is used to retrieve any worth given the important thing to make use of. Right here, we use it to retrieve the worth within the Working System’s PATH atmosphere variable. Observe within the following Golang code instance that we can’t solely retrieve values from the atmosphere variable, but additionally set them as required:

viper.BindEnv("GOMAXPROCS")
eval := viper.Get("GOMAXPROCS")
fmt.Println("GOMAXPROCS:", eval) 

viper.Set("GOMAXPROCS", 20)
eval = viper.Get("GOMAXPROCS")
fmt.Println("GOMAXPROCS:", eval)

We are able to additionally set new atmosphere variables by way of Go code, topic to the Working System’s permission, in fact:

viper.BindEnv("MYVARIABLE")
cval := viper.Get("MYVARIABLE")
if cval == nil {
	fmt.Println("MYVARIABLE couldn't be outlined.")
}

Observe that the flag package deal doesn’t supply such flexibility, however the os package deal in the usual library affords some. Nevertheless, the viper package deal makes it a lot simpler to make use of.

Learn: The Greatest Instruments for Distant Builders

How one can Learn JSON Configuration Information in Go along with viper

Generally, configuration information are written in a separate configuration file in one of many many alternative out there codecs, comparable to JSON. The viper package deal is totally geared up to learn and extract data saved there. Right here is a few fast instance code of the right way to learn a JSON configuration file in Go.

Let the JSON config file: testJSONConfig.json be as follows:

{
"init-param": {
"installAt": "Philadelphia, PA",
"adminEmail": "[email protected]",
"staticPath": "/content material/static"
},
"taglib": {
"taglib-uri":"xyz.tld",
"taglib-loc":"/WEB-INF/tlds/xyz.tld"
}
}

The Go code snippet to learn the JSON file is as follows:

viper.SetConfigType("json")
viper.SetConfigFile("./testJSONConfig.json")
fmt.Printf("Utilizing config: %sn", viper.ConfigFileUsed())
viper.ReadInConfig()

if viper.IsSet("init-param.installAt") {
fmt.Println("init-param.installAt:", viper.Get("init-param.installAt"))
} else {
fmt.Println(" init-param.installAt not set.")
}
if viper.IsSet("init-param.staticPath") {
fmt.Println("init-param.staticPath:", viper.Get("init-param.staticPath"))
} else {
fmt.Println(" init-param.staticPath is just not set.")
}

Working with different well-liked file codecs, comparable to YAML, TOML, HCL, and so forth, utilizing viper is kind of related.

Unmarshalling By way of viper in Go

Curiously, viper additionally gives the function of unmarshalling of values from configuration information to Go sorts comparable to struct, map, and so forth. Here’s a fast instance of the right way to unmarshal with viper in Go:

sort configType struct {
InstallAt string
Model string
StaticPath string
}

var config configType

err := viper.Unmarshal(&config)
if err != nil {
fmt.Println("Unmarshalling failed!")
}

Observe that the marshalling options are usually supplied by the package deal of the file format we need to marshall. For instance, if we need to marshall a Go sort right into a YAML file, then the YAML Go package deal will present the marshalling function.

Remaining Ideas on the Go Library viper

This has been a fast overview of the viper package deal, with a glimpse of its use in Go. Extra detailed data could be obtained from the viper documentation itself. Perceive that viper, in spite of everything, is a device for use in accordance with the requirement of the software program being developed. It helps many wonderful options associated to storing and retrieving configuration data sought by programmers in trendy utility growth.

Each functionality of viper might not be required for the time being, however that ought to not cease one from utilizing a few of its options. Utilizing judiciously is the important thing. For instance, it’s higher to make use of configuration information as a substitute of utilizing command line utilities to provide too many configuration parameters and flags. On this state of affairs, the options supplied by the viper package deal could be fairly useful.

Learn extra Go programming tutorials and Golang growth suggestions.