diff --git a/README.md b/README.md index a6cb60b..e4ed791 100644 --- a/README.md +++ b/README.md @@ -370,6 +370,40 @@ func main() { } ``` +## Defaults from code + +You may define default value also in code, by initialising the config data before it's filled by `env.Parse`. +Default values defined as struct tags will overwrite existing values during Parse. + +```go +package main + +import ( + "fmt" + "log" + + "github.com/caarlos0/env/v6" +) + +type Config struct { + Username string `env:"USERNAME" envDefault:"admin"` + Password string `env:"PASSWORD"` +} + +func main() { + var cfg = Config{ + Username: "test", + Password: "123456", + } + + if err := env.Parse(&cfg); err != nil { + fmt.Println("failed:", err) + } + + fmt.Printf("%+v", cfg) // {Username:admin Password:123456} +} +``` + ## Stargazers over time [![Stargazers over time](https://starchart.cc/caarlos0/env.svg)](https://starchart.cc/caarlos0/env) diff --git a/env_test.go b/env_test.go index a4171b4..25ca340 100644 --- a/env_test.go +++ b/env_test.go @@ -1157,6 +1157,25 @@ func ExampleParse_onSet() { // {Home:/tmp/fakehome Port:3000 IsProduction:false} } +func ExampleParse_Defaults() { + type config struct { + A string `env:"FOO" envDefault:"foo"` + B string `env:"FOO"` + } + + // env FOO is not set + + var cfg = config{ + A: "A", + B: "B", + } + if err := Parse(&cfg); err != nil { + fmt.Println("failed:", err) + } + fmt.Printf("%+v", cfg) + // Output: {A:foo B:B} +} + func TestIgnoresUnexported(t *testing.T) { is := is.New(t)