Read .env files in Go using Viper

Maneesha Indrachapa
5 min readAug 14, 2022

You may be wondering why we need some library named Viper to read .env files in Go lang. Can’t we read them normally using a file writer or something? Let me give an answer to that question. If you have a big project with a lot of environments and a lot of varying configuration file types you have to write a huge piece of code for that. Viper is there to save you from that trouble

What is the Viper?

According to the official GitHub documentation for the Viper,

Viper is a complete configuration solution for Go applications including 12-Factor apps. It is designed to work within an application, and can handle all types of configuration needs and formats.

Here we are going to develop a simple program where we can read the .env files.

Let's write some code 💻👾

I hope you have installed Go on your computer and here I’m not going to talk about how to install Go. If you want to check please refer to this link

To create a Go project on your computer you can simply create a folder and go inside that folder and run the below commands in terminal

when you run go mod init <module-name> this will create a module for you it is like package.json in the node.js project it will contain all the dependencies you need to run the project.

1. .env file setup

First, let's create a .env file to hold the environment details in the root directory. You can always create subdirectories for that but this is not a production-level code so here I’m going to crean an app.env file in the root folder

Here I’m using two environment variables one for the server port and the other for a secret key. To run in a certain port in Go you need to use : before the port number. That’s why I used :8000 for server port.

2. Environment Configuration read and store

Next what we need to do is create a function to read the variables from the .env file. For that, we are going to create a directory in our root directory and create an env.go file

In the env.go file first we add a package name and then we are going to create a struct.

A struct (short for “structure”) is a collection of data fields with declared data types.Golang has the ability to declare and create its own data types by combining one or more types, including both built-in and user-defined types.

Here we create a struct that contains LocalServerPort which points to the LOCAL_SERVER_PORT and SecretKey which point to SECRET_KEY in app.env file

Now we need to write the function to read the app.env file. To read the configuration files such as .env, YAML, XML, etc there is a Go package named Viper. So let's install that package on our project. Open the terminal and run the below command

then we write the below code. (I will add the full code to env.go file and explain it)

env.go

After creating the struct we create a variable var EnvConfigs *envConfigs this means this EnvConfigs is a public variable which uses the pointer type of envConfig as the base.

In Go if a variable starts with a capital letter it means it is in public scope. If a variable starts with simple letter it means it is in private scope

In the func loadEnvVariables() (config *envConfigs){} what happens is we create a function named loadEnvVariables() which return a variable named config which is a pointer type of envConfigs . First, 3 lines inside the function pointing out the viper where to locate the .env file, the type of the .env file which is .env and the name of the .env file which is app.env.

Next Viper tries to read the configs from the file and if there is an error it will log the error. this is a one-liner if..else in Go lang for error handling if you are confused with the code let me explain

Read environment variables if error, log it

The first bit of the if is known as an initialization statement, and it can be used to set up local variables. For functions that only return an error, the initialization statement is an incredibly useful tool. The error is scoped only to the if block that handles it, and our code ends up being a little easier to read.

Unmarshal

Finally in loadEnvVariables() function, viper unmarshals environment variables to the struct. Here you can see it unmarshals the variables to the &config in go & used in front of a variable means it is trying to refer to the address of that particular variable. So here viper unmarshals the values to the address of config variable.

In the func InitEnvConfigs(), we assign the value (config ) returned from loadEnvVariables() to the EnvConfigs variable.

Init function to call the loadEnvVariables function

3. Check environment configurations are successfully loading

Go to your root directory and create a file named main.go. In the main() function print the env variables

So we can see the below output when we run the main.go file using go run main.go command

env values output

Congratulations 🎉 now you know how to write a code in Go to read the environment variables. If you like this,please buy me a coffee ☕️

--

--