Skip to content

yet another Go configuration library

License

Notifications You must be signed in to change notification settings

zoido/yag-config

Repository files navigation

Yet Another Golang Config Library

go reference licence CI coverage go report

Overview

  • obtain configuration values from flags and/or environment variables (flags always take precedence)
  • any variable or struct member can become a destination for the config value
  • define defaults in the native type
  • option define environment variable prefix
  • option to override the environment variable name
  • option to mark options as required

Example

type config struct {
	Str      string
	Bool     bool
	Int      int
	Duration time.Duration
}

y := yag.New(yag.WithEnvPrefix("MY_APP_"))
cfg := &config{
	Str: "default str value",
	Int: 42,
}

y.String(&cfg.Str, "str", "sets Str")
y.Bool(&cfg.Bool, "bool", "sets Bool")
y.Duration(&cfg.Duration, "duration", "sets Duration", yag.FromEnv("MY_DURATION_VALUE"))
y.Int(&cfg.Int, "int", "sets Int")

args := []string{"-str=str flag value"}

_ = os.Setenv("MY_APP_STR", "str env value")
_ = os.Setenv("MY_APP_INT", "4")
_ = os.Setenv("MY_DURATION_VALUE", "1h")

err := y.Parse(args)
if err != nil {
	fmt.Printf("Error: %v\n", err)
	return
}

fmt.Printf("config.Str: %v, ", cfg.Str)
fmt.Printf("config.Int: %v, ", cfg.Int)
fmt.Printf("config.Bool: %v, ", cfg.Bool)
fmt.Printf("config.Duration: %v", cfg.Duration)

// Output:
// config.Str: str flag value, config.Int: 4, config.Bool: false, config.Duration: 1h0m0s

Supported types

  • str
  • int, int8, int16, int32, int64
  • uint, uint8, uint16, uint32, uint64
  • float32, float64
  • bool
  • time.Duration
  • any flag.Value implementation (e.g. (github.com/sgreben/flagvar)

Credits

Originally inspired by flags processing in of Consul agent.