Last week I started a Go project for a personal project. I need to load the environment variable from the .env file. I know how to do this for NodeJs by just installing the dotenv library, assign process.env.* to an object, and done1.

In Go, it’s not that simple. I need at least 2 libraries2 to do this, godotenv for loading the content of .env and envconfig to assign the environment variable to struct so I can get type safety.

This is how I set them up:

// main.go
package main

import (
	"fmt"

	"github.com/joho/godotenv"
	"github.com/kelseyhightower/envconfig"
)

type Config struct {
	// MYAPP_API_PORT is defined in .env
	Port string `envconfig:"API_PORT" default:"3000"`
}

func main() {
    // Load .env file and ignore the error if .env is not exist
	_ = godotenv.Overload()

	var env Config

    // "myapp" is a prefix of a key for each entry in .env file
	err := envconfig.Process("myapp", &env)
	if err != nil {
		fmt.Print("Cannot load env")
	}

	fmt.Printf("Port is %s", env.Port) // Port is 4000
}
# .env file
MYAPP_API_PORT='4000'

  1. Type safety can be achieved with TypeScript. ↩︎

  2. Actually, godotenv is enough to match dotenv functionality, but why not use envconfig as well. ↩︎