Guide to Environment variables in Go

14 Aug 2020 ⏱️ 6 min
Guide to Environment variables in Go

In this tutorial, I will be covering the basics around environment variables and some of the default and most used Golang environment variables. We will also learn how to set environment config from our golang programs.

Let’s begin!

What are the environment variables?

An environment variable is a name/value pair that is present outside of the program but can be referenced at a given time. There are a lot of environment variables which are already predefined in your system. Eg. $HOME

Trying running echo $HOME this will display your current user home directory. For me it’s like - /home/mohit . The result may vary based on your OS. Since I am using Ubuntu, the results might be different on your machine. But, concepts remains the same 😎

These environment variables can be set/unset or used anytime similar to how variables work in our programs.

You can see all the environment variables in your system with env command.


Go default Environment variables

There are many variables that come with Golang when you install it and can be configured as per use. Some of the most used ones are -

GOROOT

This is the path where the Go standard library is located on your local filesystem. You generally won’t need to modify this unless you want to use some other versions of Go as well. It is set to /usr/local/<go-version> by default

GOPATH

This variable defines the root of your workspace. It tells Go where to look for your code. It stores all the files necessary for the development of the programs. It consists of three directories -

  • /bin - where go places binaries that go install compile
  • /pkg - location of compiled package code
  • /src - where your go code resides

By default, it is unset and points to a subdirectory named go in the user’s home directory. ($HOME/go on Unix, %USERPROFILE%\go on Windows)

Note from official Go docs. In module-aware mode -

  • Module cache is stored in the pkg/mod subdirectory of the first GOPATH directory.
  • Module source code outside the cache may be stored in any directory.
  • If GOPATH is not set, it defaults to the go subdirectory of the user’s home directory.

GOPROXY

A Go module proxy is any web server that can respond to GET requests for URLs of a specified form.

GO proxy allows control over the download source and provides caching as well. This serves the zip archive of source code over HTTP making it faster.

You can use the proxy server by setting -

export GOPROXY=https://proxy.golang.org/

The above proxy is run by the Go team. To make changes permanent , add it to ~/.bashrc.

GOOS

GOOS defines the operating system for which to compile code. Examples are linux, darwin, windows, etc. This is an optional environment variable by default is set to empty.


Setting custom Env. variables/Configs in Go

Now that you have learned the basics of environment variables and some default ones provided by Go, you might be wondering to use it in your own projects. Configs should be used to store all kind of important information which can be easy to change. This also provides additional security to your passwords, secret keys to be directly available in your source code and are visible to anyone who has access to code.

Also, various environments require different configs. Like you would want to give different config in your test/development servers to those of production servers.

That’s a lot of explanation but it was required so that you don’t push secrets and use configs. There are a lot of ways to manage configs in go projects via .env,.json,.yaml, .toml and other formats. For simplicity, for now we will set the environment variables via code -

package main

import (
    "fmt"
    "os"
)

func main() {
    // Set an environment variable
    os.Setenv("SOME_VARIABLE", "SOME_VALUE")

    // Get the environment variable we set in previous step
    value := os.Getenv("SOME_VARIABLE")
    fmt.Println(value)

    // Unset an Environment Variable
    os.Unsetenv("SOME_VARIABLE")
    fmt.Println("After unset -> ", os.Getenv("SOME_VARIABLE"))
}
# Output
SOME_VALUE
After unset ->

Here, the program is pretty straightforward where we first set the variable and then fetch it with os.Getenv(), then we unset it using os.Unsetenv()

There are a couple of other useful methods -

  • os.Environ() - This returns all the environment variable which are set in key=value format.
  • os.LookupEnv() - This function combines the functionality of checking whether such variable exists, if yes then it returns the value.
  • os.Clearenv()- This method deletes all the environment variables and is useful when we are writing tests.

Well, it is not a good practice to use these secrets in your code directly. To solve this there are a number of libraries like godotenv, etc.

Here, the code below uses godotenv - You can get it using go get github.com/joho/godotenv

package main

import (
    "log"
    "github.com/joho/godotenv"
    "fmt"
    "os"
)

// init() is invoked before main()
// Loading variables before main() runs
func init() {
    // loads values from .env into the system
    if err := godotenv.Load(); err != nil {
        log.Print(".env file not found")
    }
}

func main() {
    // Get the REDIS_PORT environment variable
    redisPort, found := os.LookupEnv("REDIS_PORT")
    if found {
        fmt.Println(redisPort)
    }
}

// Output based on .env below
6379

In this code, we first load the environment variables from a .env file in this project directory. Then, we fetch the REDIS_PORT key. The .env file looks like -

REDIS_PORT=6379

In case you are looking for pre-shipped packages, There are many useful open-source packages which help in managing environment configs -


Resources

Awesome! You just learned how to manage configs in Golang. There are couple of other ways to manage configs in a better way, will cover them in some other article. I hope now you can easily add configs in your projects.

Liked the article? Consider supporting me ☕️


I hope you learned something new. Feel free to suggest improvements ✔️

I share regular updates and resources on Twitter. Let’s connect!

Keep exploring 🔎 Keep learning 🚀

Liked the content? Do support :)

Paypal - Mohit Khare
Buy me a coffee