The viper Package: Using Command-Line Flags

Let’s learn about the viper package.

Now that we know about working with JSON, XML, and YAML data in Go, we are ready to learn about the viper package.

The flag package

Flags are specially formatted strings that are passed into a program to control its behavior. Dealing with flags on our own might become very frustrating if we want to support multiple flags and options. Go offers the flag package for working with command-line options, parameters, and flags.

The viper package

Although flag can do many things, it is not as capable as other external Go packages. Thus, if we are developing simple UNIX system command-line utilities, we might find the flag package very interesting and useful. Of course, creating simple command-line utilities isn’t the primary learning objective of this course! Therefore, we’ll skip the flag package and introduce an external package named viper, which is a powerful Go package that supports a plethora of options. viper uses the pflag package instead of flag, which is also illustrated in the code we will look at in the following sections.

All viper projects follow a pattern. First, we initialize viper, and then we define the elements that interest us. After that, we get these elements and read their values in order to use them. The desired values can be taken either directly, as happens when we are using the flag package from the standard Go library, or indirectly using configuration files. When using formatted configuration files in the JSON, YAML, TOML, HCL, or Java properties format, viper does all the parsing for us, which saves us from having to write and debug lots of Go code. viper also allows us to extract and save values in Go structures. However, this requires that the fields of the Go structure match the keys of the configuration file.

The home page of viper is on GitHub. Please note that we are not obliged to use every capability of viper in our tools—just the features that we want. The general rule is to use the features of Viper that simplify our code. Put simply, if our command-line utility requires too many command-line parameters and flags, then it would be better to use a configuration file instead.

Using command-line flags

The first example shows how to write a simple utility that accepts two values as command-line parameters and prints them on screen for verification. This means that we are going to need two command-line flags for these parameters.

Starting from Go version 1.16, using modules is the default behavior, which the viper package needs to use. So, we need to put useViper.go, which is the name of the source file, inside ~/go for things to work. For the GitHub username educative we will run the following commands:

Get hands-on with 1200+ tech skills courses.