#best-practice #development #golang #pattern

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:

1ENVIRONMENT=development
2VERSION=1

Load the .env file:

 1package main
 2
 3import (
 4    "fmt"
 5    "log"
 6    "github.com/joho/godotenv"
 7)
 8
 9func main() {
10    err := gotdotenv.Load() // 👈 load .env file
11    if err != nil {
12        log.Fatal(err)
13    }
14
15    environment := os.Getenv("ENVIRONMENT")
16
17    fmt.Println(environment)
18
19    version := os.Getenv("VERSION")
20
21    versionNum, err := strconv.Atoi(version)
22    if err != nil {
23        log.Fatal(err)
24    }
25
26    fmt.Println(versionNum)
27}

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.

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

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.

 1package main
 2
 3import (
 4    "fmt"
 5    "log"
 6
 7    "github.com/caarlos0/env/v9"
 8    "github.com/joho/godotenv"
 9)
10
11type Config struct {
12    Environment string `env:"ENVIRONMENT,required"`
13    Version     int    `env:"VERSION,required"`
14}
15
16func main() {
17    // Loading the environment variables from '.env' file.
18    err := godotenv.Load()
19    if err != nil {
20        log.Fatalf("unable to load .env file: %e", err)
21    }
22
23    cfg := Config{} // 👈 new instance of `Config`
24
25    err = env.Parse(&cfg) // 👈 Parse environment variables into `Config`
26    if err != nil {
27        log.Fatalf("unable to parse ennvironment variables: %e", err)
28    }
29
30    fmt.Println("Config:")
31    fmt.Printf("Environment: %s\n", cfg.Environment)
32    fmt.Printf("Version: %d\n", cfg.Version)
33}

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