In this article you are going to learn how to load environment variables in Go. First you will learn how to load environment variables from a .env file using godotenv, then you will learn how to use the env package to parse environment variables into a struct.

Loading .env file

One of the common practice when developing backend services is to load environment variables from a .env file, specially when running a service locally.

You can use a package called godotenv to load environment variables from a .env file.

Install the godotenv package:

go get github.com/joho/godotenv

Prepare a .env file:

ENVIRONMENT=development
VERSION=1

Load the .env file:

package main

import (
    "fmt"
    "log"
    "github.com/joho/godotenv"
)

func main() {
    err := gotdotenv.Load() // 👈 load .env file
    if err != nil {
        log.Fatal(err)
    }

    environment := os.Getenv("ENVIRONMENT")

    fmt.Println(environment)

    version := os.Getenv("VERSION")

    versionNum, err := strconv.Atoi(version)
    if err != nil {
        log.Fatal(err)
    }

    fmt.Println(versionNum)
}

In Go you can use os.Getenv function to get environment variables, it returns a string so if you are loading a number or boolean you would have to parse it on your own.

Parsing environment variables

Now you will learn how to parse environment variables into a struct using env a quite popular Go package. Using this package will save you a lot of time and will result in less and more cleaner code.

Install the env package:

go get github.com/caarlos0/env/v9

env uses struct tags to parse and load environment variables. Let's write a struct to present the environment variables from our .env file.

type Config struct {
    Environment string `env:"ENVIRONMENT,required"`
    Version     int    `env:"VERSION,required"`
}

env will automatically check the type of the property and try to parse it, for example in above struct Config, Version is of type int, env will try to read the VERSION environment variable and try to parse it as an int.

Now all you have to do is create an instace of Config and call the env.Parse function.

package main

import (
    "fmt"
    "log"

    "github.com/caarlos0/env/v9"
    "github.com/joho/godotenv"
)

type Config struct {
    Environment string `env:"ENVIRONMENT,required"`
    Version     int    `env:"VERSION,required"`
}

func main() {
    // Loading the environment variables from '.env' file.
    err := godotenv.Load()
    if err != nil {
        log.Fatalf("unable to load .env file: %e", err)
    }

    cfg := Config{} // 👈 new instance of `Config`

    err = env.Parse(&cfg) // 👈 Parse environment variables into `Config`
    if err != nil {
        log.Fatalf("unable to parse ennvironment variables: %e", err)
    }

    fmt.Println("Config:")
    fmt.Printf("Environment: %s\n", cfg.Environment)
    fmt.Printf("Version: %d\n", cfg.Version)
}

Check out the env package it has lots of more features.