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/v6
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/v6"
"github.com/joho/godotenv"
)
type Config struct {
Environment string `env:"ENVIRONMENT,required"`
Version int `env:"VERSION,required"`
}
func main() {
err := godotenv.Load()
if err != nil {
log.Fatalf("unable to load .env file: %e", err)
}
cfg := Config{}
err = env.Parse(&cfg)
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.