DEV Community

Cover image for Reading from Go's .Env
Kate Efimova
Kate Efimova

Posted on • Updated on

Reading from Go's .Env

A black text divider

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"
)
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

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

}
Enter fullscreen mode Exit fullscreen mode

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")
    }
}
Enter fullscreen mode Exit fullscreen mode

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

}
Enter fullscreen mode Exit fullscreen mode

The output

Terminal logs "Jade is 34 years old."

A black text divider

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)

Collapse
 
alexsuslov profile image
Alex Suslov

Best way is replace os.Getenv("NAME_TOKEN") with GetPanic("NAME_TOKEN").

// https://github.com/alexsuslov/godotenv/blob/master/load.go
// GetPanic get variable or panic
func GetPanic(key string) string {
    v, _ := syscall.Getenv(key)
    if v == "" {
        panic(key)
    }
    return v
}
Collapse
 
alexsuslov profile image
Alex Suslov • Edited

Some more:

Micro service version from git

var version=""
func main(){
  log.Printf("Starting  %v \n", version)
}

Build

go build -ldflags "-X main.version=`git describe --abbrev=0`" main.go
Collapse
 
wrldwzrd89 profile image
Eric Ahnell

As someone who doesn't know Go much more than you do, and wants to learn, this helps!

Collapse
 
arturoaviles profile image
Arturo Avilés

Great tutorial! Thanks Kate!

Collapse
 
alexsuslov profile image
Alex Suslov

Variables maybe load in docker env

if err := godotenv.Load(); err != nil {
  log.Println("warning .env file load error", err)
}