Reading from Go's .Env
Tags: go, programming, notes
Published: 2020-02-07 06:18:56

---
title: Reading from Go's .Env
published: true
description: Quick tutorial on how to read from .env files in Go
cover_image: https://icdn2.digitaltrends.com/image/digitaltrends/kostenlose_programme_bildbearbeitung_1.jpg
tags: Go, Programming, Notes
---

<img src="https://thepracticaldev.s3.amazonaws.com/i/bzr47frhmg7w17i22gw9.png"  alt="A black text divider" height="50%" width="50%">


#  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](https://tutorialedge.net/golang/writing-a-twitter-bot-golang/), 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:
```go
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. 
```go
type human struct {
	Name string
	Age  string
}
```

Now lets start writing our main. 
```go
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:
```go
// 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!

```go
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
![Terminal logs "Jade is 34 years old."](https://dev-to-uploads.s3.amazonaws.com/i/egc7igfobw51ztr8imce.png)

<img src="https://thepracticaldev.s3.amazonaws.com/i/bzr47frhmg7w17i22gw9.png"  alt="A black text divider" height="50%" width="50%">

#  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!