Monday, October 3, 2022
HomeSoftware DevelopmentIntroduction to Viper in Go and Golang

Introduction to Viper in Go and Golang

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

Trying to study Go or Golang in an internet course surroundings? We now have an inventory of the Greatest On-line Programs to Be taught Go and Golang that will help you get began.

What’s the viper Library in Go and Golang?

As talked about, viper is a bundle that gives an entire configuration resolution in a Go venture. Managing and sustaining configuration for an enormous and complex software – reminiscent of constructing a server software or every other software which relies upon rather a lot on person manipulation of configurations – shouldn’t be a straightforward job. Furthermore, fashionable functions are constructed to deploy in several types of environments, reminiscent of in Docker, cloud infrastructures, and so forth. Consequently, as a way to preserve consistency throughout deployment, functions needs to be constructed to be open from little to excessive configurability. An exterior help that helps on this respect shouldn’t be solely a respite, but in addition very a lot welcome for the builders concerned in constructing such an answer.

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

Learn: The way to Use the flag Bundle in Go

What Does the viper Library Assist in Go?

In accordance with the viper documentation, it helps the next in Go functions:

  • Studying JSON, TOML, YAML, HCL, envfile and Java properties config information. Most configuration info of an software is written on this format. Viper helps most of them.
  • Establishing default configurations
  • Studying surroundings variables
  • Studying distant configuration programs
  • Studying from command line flags
  • Studying from buffer
  • Setting express values

The way to Set up viper in Go

The steps to put in viper are just like putting in every other bundle in Go. As soon as a Go software venture has been arrange correctly with the required module file utilizing the go mod init command, a go.mod file can be created. This file maintains the checklist of packages used within the present venture. Simply kind: go get to put in the viper bundle. Observe {that a} new checklist of packages associated to the viper bundle can be added within the go.mod file.

Go viper Code Instance

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

bundle fundamental

import (

func fundamental() {
val := viper.Get("PATH")
fmt.Println("PATH:", val)

Notice that, within the perform fundamental(), we used viper.BindEnv to bind a viper key to the surroundings variable referred to as PATH. It’s case delicate, which means, as the secret’s offered, it can use the surroundings key that matches the important thing in uppercase if given in uppercase. Since, BindEnv can take multiple argument, every will characterize surroundings variable names that bind to this key and can be taken within the specified order.

The viper.Get perform 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 surroundings variable. Observe within the following Golang code instance that we can’t solely retrieve values from the surroundings variable, but in addition set them as required:

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 surroundings variables via Go code, topic to the Working System’s permission, after all:

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

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

Learn: The Greatest Instruments for Distant Builders

The way to Learn JSON Configuration Information in Go together with viper

Generally, configuration information are written in a separate configuration file in one of many many various out there codecs, reminiscent of JSON. The viper bundle is absolutely outfitted to learn and extract info saved there. Right here is a few fast instance code of how you can 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": {

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

fmt.Printf("Utilizing config: %sn", viper.ConfigFileUsed())

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 shouldn't be set.")

Working with different fashionable file codecs, reminiscent of YAML, TOML, HCL, and so forth, utilizing viper is kind of comparable.

Unmarshalling By way of viper in Go

Apparently, viper additionally gives the function of unmarshalling of values from configuration information to Go varieties reminiscent of struct, map, and so forth. Here’s a fast instance of how you can unmarshal with viper in Go:

kind configType struct {
InstallAt string
Model string
StaticPath string

var config configType

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

Notice that the marshalling options are sometimes offered by the bundle of the file format we need to marshall. For instance, if we need to marshall a Go kind right into a YAML file, then the YAML Go bundle will present the marshalling function.

Closing Ideas on the Go Library viper

This has been a fast overview of the viper bundle, with a glimpse of its use in Go. Extra detailed info might be obtained from the viper documentation itself. Perceive that viper, in any case, is a instrument for use in accordance with the requirement of the software program being developed. It helps many wonderful options associated to storing and retrieving configuration info sought by programmers in fashionable software growth.

Each functionality of viper might not be required in the intervening time, 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 an alternative of utilizing command line utilities to produce too many configuration parameters and flags. On this scenario, the options offered by the viper bundle might be fairly useful.

Learn extra Go programming tutorials and Golang growth suggestions.



Please enter your comment!
Please enter your name here

Most Popular

Recent Comments