08
Mar
2021

Reading and Writing Environment Variables in Go

An environment variable is a way to supply dynamic configuration information to programs at runtime. Environment variables are often used to make the same program work in different environments like Local, QA, or Production.

Get, Set, Unset, and Expand environment variables in Go

The following program demonstrates how to work with environment variables in Go. It makes use of the following functions provided by the os package:

  • os.Setenv(key, value): Set an environment variable.
  • os.Getenv(key): Get the value of an environment variable. If the environment variable is not present, it returns empty. To distinguish between an empty value and an unset value, use LookupEnv
  • os.Unsetenv(key): Unset an environment variable.
  • os.LookupEnv(key): Get the value of an environment variable and a boolean indicating whether the environment variable is present or not. It returns a string and a boolean – The boolean will be false if the environment variable is not present.
  • os.ExpandEnv(str): Expand a string by replacing ${var} or $var in the string according to the values of the current environment variables.
package main

import (
	"fmt"
	"os"
)

func main() {
	// Set an Environment Variable
	os.Setenv("DB_HOST", "localhost")
	os.Setenv("DB_PORT", "5432")
	os.Setenv("DB_USERNAME", "root")
	os.Setenv("DB_PASSWORD", "admin")
	os.Setenv("DB_NAME", "test")

	// Get the value of an Environment Variable
	host := os.Getenv("DB_HOST")
	port := os.Getenv("DB_PORT")
	fmt.Printf("Host: %s, Port: %s\n", host, port)

	// Unset an Environment Variable
	os.Unsetenv("DB_PORT")
	fmt.Printf("After unset, Port: %s\n", os.Getenv("DB_PORT"))

	/*
		Get the value of an environment variable and a boolean indicating whether the
		environment variable is present or not.
	*/
	driver, ok := os.LookupEnv("DB_DRIVER")
	if !ok {
		fmt.Println("DB_DRIVER is not present")
	} else {
		fmt.Printf("Driver: %s\n", driver)
	}

	// Expand a string containing environment variables in the form of $var or ${var}
	dbURL := os.ExpandEnv("postgres://$DB_USERNAME:$DB_PASSWORD@DB_HOST:$DB_PORT/$DB_NAME")
	fmt.Println("DB URL: ", dbURL)

}
# Output
Host: localhost, Port: 5432
After unset, Port:
DB_DRIVER is not present
DB URL:  postgres://root:admin@DB_HOST:/test

List and Clear all environment variables in Go

  • os.Environ(): This function returns a []string containing all the environment variables in the form of key=value.
  • os.Clearenv(): This function deletes all the environment variables. It may come in handy while writing tests to start with a clean environment.

The following example demonstrates how to use these two functions:

package main

import (
	"fmt"
	"os"
	"strings"
)

func main() {

	// Environ returns a copy of strings representing the environment,
	// in the form "key=value".
	for _, env := range os.Environ() {
		// env is
		envPair := strings.SplitN(env, "=", 2)
		key := envPair[0]
		value := envPair[1]

		fmt.Printf("%s : %s\n", key, value)
	}

	// Delete all environment variables
	os.Clearenv()

	fmt.Println("Number of environment variables: ", len(os.Environ()))
}
# Output
TERM_SESSION_ID : w0t0p1:70C49068-9C87-4032-9C9B-49FB6B86687B
PATH : /Users/fusebes/.nvm/versions/node/v10.0.0/bin:/usr/local/sbin:/usr/local/sbin:/Users/fusebes/protobuf/bin:/Users/fusebes/go/bin:/Users/fusebes/vaultproject:/Users/fusebes/google-cloud-sdk/bin:/Users/fusebes/.rbenv/bin:/Users/fusebes/.rbenv/shims:/Users/fusebes/anaconda3/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/fusebes/Library/Android/sdk/platform-tools:/opt/flutter/bin
.... # Output truncated for brevity

Number of environment variables:  0
Share

Yaniv Levy

Yaniv Levy, Entrepreneur, visioner & technology passionate with over 20 years on vast experience as a Senior Software Engineer and a Software Architect.

You may also like...