Preface
When you are just starting out with Go, it might be a bit overwhelming to grasp how the language works right away. As I was following this tutorial, to my surprise it logged all .env variables as undefined. It was not easy to then find a simple article covering how to properly read from an .env file in Go.
This is a super quick tutorial from someone who just learned it as well. Enjoy!
Code Example
Let's start by importing needed dependencies:
package main
import (
// Needed for terminal printing, similar to "console.log" in Node.js
"fmt"
// Helpful for logging errors
"log"
// Needed for accessing .env file
"os"
// Needed for importing/loading .env file
"github.com/joho/godotenv"
)
Then let's write a type structure, I used Human for simplicity's sake. Any human needs to have a name and a secret age. After all, isn't there a saying that it is inappropriate to ask people about their age?
I also simplified age to a string so that someone could be "20" or "twenty" years old.
type human struct {
Name string
Age string
}
Now lets start writing our main.
func main() {
// Creates a variable 'creds' in memory and assigns
// it to an object with type 'human'
creds := human{
// Given that name is stored as "NAME_TOKEN=Jade" & age is
// "AGE_SECRET_TOKEN=34", we now can ask Getenv to give us
// the value of a token based on the provided key.
Name: os.Getenv("NAME_TOKEN"),
Age: os.Getenv("AGE_SECRET_TOKEN"),
}
// Simply prints "Jade is 34 years old." to check
// that we correctly read from the .env file
fmt.Println(creds.Name + " is " + creds.Age + " years old.")
}
If you were following with me until this point, you'd probably realize that running go run [filename].go
won't give much result. That is because right now we are trying to read from something we haven't imported yet! Let's fix this:
// Init is called right on top of main
func init() {
// Loads the .env file using godotenv.
// Throws an error is the file cannot be found.
if err := godotenv.Load(); err != nil {
log.Print("No .env file found")
}
}
Here's what we have by putting all the little pieces together. Good luck,
and let me know if you need more clarification!
package main
import (
"fmt"
"log"
"os"
"github.com/joho/godotenv"
)
type human struct {
Name string
Age string
}
func init() {
if err := godotenv.Load(); err != nil {
log.Print("No .env file found")
}
}
func main() {
creds := human{
Name: os.Getenv("NAME_TOKEN"),
Age: os.Getenv("AGE_SECRET_TOKEN"),
}
fmt.Printf(creds.Name + " is " + creds.Age + " years old.")
}
The output
On a personal note
For the first time I didn't let perfectionism consume me when writing something! This article, if I can call it that way, was meant more as a way for me to store notes than anything else. So if you have any feedback on how to improve the above code, do let me know and I will fix it!
Top comments (5)
Best way is replace os.Getenv("NAME_TOKEN") with GetPanic("NAME_TOKEN").
Some more:
Micro service version from git
Build
As someone who doesn't know Go much more than you do, and wants to learn, this helps!
Great tutorial! Thanks Kate!
Variables maybe load in docker env