MCPcopy Create free account
hub / github.com/caarlos0/env / Example_setDefaultsForZeroValuesOnly

Function Example_setDefaultsForZeroValuesOnly

example_test.go:462–482  ·  view source on GitHub ↗

You can avoid setting defaults for non zero values This could be useful for loading data from config file first and then filling the rest from env

()

Source from the content-addressed store, hash-verified

460// This could be useful for loading data from config file first
461// and then filling the rest from env
462func Example_setDefaultsForZeroValuesOnly() {
463 type Config struct {
464 Username string `env:"USERNAME" envDefault:"admin"`
465 Password string `env:"PASSWORD" envDefault:"qwerty"`
466 }
467
468 cfg := Config{
469 Username: "root",
470 }
471
472 if err := ParseWithOptions(&cfg, Options{
473 Environment: map[string]string{},
474 SetDefaultsForZeroValuesOnly: true,
475 }); err != nil {
476 fmt.Println(err)
477 }
478
479 fmt.Printf("%+v", cfg)
480 // Without SetDefaultsForZeroValuesOnly, the username would have been 'admin'.
481 // Output: {Username:root Password:qwerty}
482}
483
484// An environment variable that is set but empty falls back to envDefault.
485func Example_parseEmptyEnvFallsBackToDefault() {

Callers

nothing calls this directly

Calls 1

ParseWithOptionsFunction · 0.85

Tested by

no test coverage detected