Walking throught golang struct to fullfil its fields from ENV variables.
$ go get github.com/vkd/gowalker
import (
"log"
"os"
"github.com/vkd/gowalker"
"github.com/vkd/gowalker/config"
)
type Config struct {
LogLevel string `flag:"loglevel" env:"LOGLEVEL" required:"true"`
Timeout time.Duration `default:"3s"`
DB struct {
Port int `default:"5432" flag:"db-port" env:"DB_PORT"`
}
}
func ParseConfig() {
var cfg Config
err := config.Walk(&cfg, log.New(os.Stdout, "", 0),
gowalker.Flags(gowalker.FieldKey("flag", gowalker.Fullname("-", strings.ToLower)), os.Args),
gowalker.Envs(gowalker.FieldKey("env", gowalker.Fullname("_", strings.ToUpper)), os.LookupEnv),
gowalker.Tag("default"),
gowalker.Required("required"),
)
if err != nil {
if errors.Is(err, gowalker.ErrPrintHelp) {
return nil
}
...
}
}