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
packagemainimport("fmt""os")funcmain(){// 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:
$
go get "github.com/joho/godotenv"
Create your .env file in the root of your project:
1
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
packagemainimport("fmt""os"_"github.com/joho/godotenv/autoload")funcmain(){// godotenv/autoload will load in from .env file
// This then prints out MYSECRET's value
fmt.Println(os.Getenv("MYSECRET"))}
Edd is a PHP and Go developer who enjoys blogging about his experiences, mostly about creating and coding new things he's working on and is a big beliver in open-source and Linux.