Skip to content
/ gowalker Public

Golang struct walker. Loads ENV variables into Golang struct fields.

License

Notifications You must be signed in to change notification settings

vkd/gowalker

Repository files navigation

Golang struct walker

Build Status codecov Go Report Card GoDoc Sourcegraph Release

Walking throught golang struct to fullfil its fields from ENV variables.

Install

$ go get github.com/vkd/gowalker

Example of the config parsing

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
		}
		...
	}
}