Using a .env File & Environment Variables

Environment variables are used throughout the coding ecosystem as a way of keeping secrets out of the code. They’re also useful as a way of keeping the code the same between environments, e.g. live, uat and test servers but functionality might work differently.

This post sets out to explain the basics of getting these variables, setting them and easily using your own when in your local environment.

Basics: Get & Set

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
Copy to Clipboard
package main

import (
	"fmt"
	"os"
)

func main() {

	// Example of using an env var
	// e.g. will print out "en_GB.UTF-8"
	myLang := os.Getenv("LANG")
	fmt.Println(myLang)

	// How to dynamically set an env var
	os.Setenv("MYENV", "myvalue")
}

From .env file:

Run:

$
Copy to Clipboard
go get "github.com/joho/godotenv"

Create your .env file in the root of your project:

1
Copy to Clipboard
MYSECRET=1234

Read from environment file. This uses the pre-made autoload file to load in a .env file - if it exists. This is useful, as you may have a .env file for local development and not in production systems.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
Copy to Clipboard
package main

import (
	"fmt"
	"os"

	_ "github.com/joho/godotenv/autoload"
)

func main() {

	// godotenv/autoload will load in from .env file

	// This then prints out MYSECRET's value
	fmt.Println(os.Getenv("MYSECRET"))
}