Package envconfig
provides functionality to easily populate your config structure by using both environment variables, and a .env file (optional).
go get github.com/h-dav/envconfig/v2
required
:true
orfalse
default
: Default value if environment variable is not set.prefix
: Used for nested structures.envjson
: Used for deserialising json into config.- Text Replacement:
${EXAMPLE}
can be used to insert other environment variables.
- string (slice compatible)
- int (slice compatible)
- float (slice compatible)
- bool
- time.Duration
package main
import (
"time"
"github.com/h-dav/envconfig/v2"
)
type Config struct {
// Fields must be exported to be populated.
LogLevel string `env:"LOG_LEVEL" default:"info"`
Server struct {
Port string `env:"PORT" required:"true"`
} `prefix:"SERVER_"`
JSONField struct {
First string `json:"first"`
} `envjson:"JSON_FIELD"`
SliceIntField []int `env:"SLICE_INT_FIELD"`
DurationField time.Duration `env:"DURATION"`
}
func main() {
var cfg Config
if err := envconfig.Set("./config/default.env", &cfg); err != nil {
...
}
}
Corresponding .env file:
LOG_LEVEL=debug
SERVER_PORT=8080
JSON_FIELD={"first": "example"}
SLICE_INT_FIELD=1, 2, 3
DURATION=30s
Note
See test cases for more usage examples.
Note
This package takes heavy inspiration from httputil for handling reflection.