Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,12 @@ You can see the full documentation and list of examples at [pkg.go.dev](https://
> `envDefault` value, if any. Neither `required` nor `notEmpty` guard against
> this: `required` is satisfied by the default, while `notEmpty` only sees the
> value after the default has been applied.
>
> With an `envDefault` in place, `env` cannot tell a variable that is set to an
> empty value from one that is not set at all. If that difference matters for a
> field, leave out the `envDefault`: `notEmpty` then rejects the empty value,
> and `os.LookupEnv` lets you apply a fallback only when the variable is really
> unset.

### Functions

Expand Down
21 changes: 16 additions & 5 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -482,15 +482,26 @@ func Example_setDefaultsForZeroValuesOnly() {
}

// An environment variable that is set but empty falls back to envDefault.
//
// Neither `required` nor `notEmpty` guards against this: `required` is already
// satisfied by the default, and `notEmpty` only sees the value after the
// default was applied.
func Example_parseEmptyEnvFallsBackToDefault() {
type Config struct {
Foo string `env:"FOO" envDefault:"fallback"`
Foo string `env:"EMPTY_FOO" envDefault:"fallback"`
Bar string `env:"EMPTY_BAR,notEmpty" envDefault:"fallback"`
Baz string `env:"EMPTY_BAZ,required" envDefault:"fallback"`
}

os.Setenv("FOO", "")
os.Setenv("EMPTY_FOO", "")
os.Setenv("EMPTY_BAR", "")
os.Setenv("EMPTY_BAZ", "")

cfg, _ := ParseAs[Config]()
cfg, err := ParseAs[Config]()
if err != nil {
fmt.Println(err)
}

fmt.Println(cfg.Foo)
// Output: fallback
fmt.Printf("%+v", cfg)
// Output: {Foo:fallback Bar:fallback Baz:fallback}
}