Using a .env File & Environment Variables (original) (raw)

Written byEdd Turtle on gophercoding.com
on 3rd of June 2022

(Updated: 2nd of April 2023)

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 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:

1 go get "github.com/joho/godotenv"

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

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 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")) }

Author Edd Turtle

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.

Tweet me!☕ Buy me a Coffee