Skip to content

Commit

Permalink
docs: default values by filling the structure (#195)
Browse files Browse the repository at this point in the history
* fix: Add a sample that shows how default values may be pre initialized in code and how parse may overwrite with default values from tags.

* Apply suggestions from code review

Co-authored-by: nils <gittyD0g>
Co-authored-by: Carlos Alexandro Becker <caarlos0@users.noreply.github.com>
  • Loading branch information
Nils Wogatzky and caarlos0 authored Oct 15, 2021
1 parent db06a3f commit e508d58
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 0 deletions.
34 changes: 34 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
19 changes: 19 additions & 0 deletions env_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down

0 comments on commit e508d58

Please sign in to comment.