DEV Community

Cover image for How to read env variables in Golang using viper
Dev Niklesh
Dev Niklesh

Posted on • Updated on

How to read env variables in Golang using viper

Using Env variables are one of the ways to secure your app's secrets and it is widely used in almost all the applications.

You have to be aware of such production practices to secure your application!

In this blog we will read environment variables (store our secret keys securely) using viper package from GO.

I have kept this post simple yet informative so, Let's jump right into it!

Project Setup

Here we create the project structure for this tutorial.

I suggest you to glance through this section even if you already have a project ready. This will help you understand this tutorial better.

1. Start a new GO project

Go to go workspace

cd $GOPATH
Enter fullscreen mode Exit fullscreen mode

Create a project and go to the project

mkdir read-env-var
cd read-env-var
Enter fullscreen mode Exit fullscreen mode

2. Initialize the project

go mod init github.com/YOUR_USERNAME/read-env-var
Enter fullscreen mode Exit fullscreen mode

3. Let's create the project structure

mkdir -p cmd pkg/common/envs pkg/common/config
Enter fullscreen mode Exit fullscreen mode

4. Create files

touch Makefile cmd/main.go pkg/common/envs/.env pkg/common/config/config.go
Enter fullscreen mode Exit fullscreen mode

Finally, your project structure should look like this,

Project structure

Environment Variables

First, we need to add some environment variables where we store the application port and other secrets.

Let’s add code to pkg/common/envs/.env

PORT=:3000
DB_URL=postgres://DB_USER:DB_PASSWORD@DB_HOST:DB_PORT/go_api_medium
API_KEY=<YOUR_API_KEY_HERE>
Enter fullscreen mode Exit fullscreen mode

Install viper

Viper is the package, that we will be using to read the env variable and use it in our project

go get github.com/spf13/viper
Enter fullscreen mode Exit fullscreen mode

Viper Configuration

Let’s add code to pkg/common/config/config.go

package config

import "github.com/spf13/viper"

type Config struct {
    Port  string `mapstructure:"PORT"`
    DBUrl string `mapstructure:"DB_URL"`
}

func LoadConfig() (c Config, err error) {
    viper.AddConfigPath("./pkg/common/config/envs")
    viper.SetConfigName("dev")
    viper.SetConfigType("env")

    viper.AutomaticEnv()

    err = viper.ReadInConfig()

    if err != nil {
        return
    }

    err = viper.Unmarshal(&c)

    return
}
Enter fullscreen mode Exit fullscreen mode

Main file

We will initialize viper to handle our env variables

Let’s add code to cmd/main.go

package main

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

func main() {
    viper.SetConfigFile("./pkg/common/envs/.env")
    viper.ReadInConfig()

    // add env variables as needed
    port := viper.Get("PORT").(string)
    dbUrl := viper.Get("DB_URL").(string)

    fmt.Println(port, dbUrl)
}
Enter fullscreen mode Exit fullscreen mode

Run the code

Let add our script in MakeFile

server:
     go run cmd/main.go
Enter fullscreen mode Exit fullscreen mode

and then, run make server script in terminal

(or)

Directly run command in terminal

go run cmd/main.go
Enter fullscreen mode Exit fullscreen mode

Output:

Output

That's it folks. To summarise, we

  1. Created a Go project
  2. Added env variables
  3. Installed viper package
  4. Added viper configuration
  5. Initialised viper in main.go file

In the next tutorial, we will extend this project to add CRUD API using Gin framework. Make sure to follow and like this tutorial. Thanks for being here!

Please share it with your friends & colleagues.

Top comments (0)