Go Env
This is a Go library that reads configuration from file (.env.tkl in the current working directoy by default) to update the given struct.
The configuration is in Tickle configuration format.
If the configuration file doesn't exist, the configuration is loaded from environment variables.
Interface
import (
"codeberg.org/yuce/go-env"
)
type Config struct {
APIKey string `env:"API_KEY"`
ServerAddress string `env:"SERVER_ADDRESS"`
}
// load configuration from .env.tkl file if it exists, or environment variables
var cfg Config
if err := env.Load(&cfg); err != nil {
panic(err)
}
// load configuration from the given path if it exists, or environment variables
var cfg Config
if err := env.LoadFromPath("sample.tkl", &cfg); err != nil {
panic(err)
}
Behaviour
The configuration from the Tickle file is tried first.
The default Tickle file is named .env.tkl, which is searched in the current working directory.
If it doesn't exist, the configuration is loaded from environment variables.
The name of the environment variable corresponding to a struct field is take from the struct field tagged env.
The following types are supported as field types in the target struct:
string
int, int16, int32, int64 and their unsigned variants
float32, float64
bool. false string is mapped to false, true string is mapped to true.
Examples
Given the following struct:
type ServerConfig struct {
Host string `ms:"HOST"`
Port int `ms:"PORT"`
Enabled bool `ms:"ENABLED"`
}
Example 1
$PWD/.env.tkl exists, and has the following contents:
HOST: "yuce.me"
PORT: 8080
ENABLED: true
The Go code below:
var cfg ServerConfig
err := env.Load(&cfg)
// err == nil
Results with the following values in the cfg struct:
cfg.Host == "yuce.me"
cfg.Port == 8080
cfg.Enabled == true
Example 2
$PWD/.env.tkl doesn't exist, and the following environment variables are defined:
HOST="foo.bar"
PORT=1234
ENABLED=false
The Go code below:
var cfg ServerConfig
err := env.Load(&cfg)
// err == nil
Results with the following values in the cfg struct:
cfg.Host == "foo.bar"
cfg.Port == 1234
cfg.Enabled == false