Skip to content

Commit

Permalink
Lookup env and toml field tags when flag is not given (#6)
Browse files Browse the repository at this point in the history
  • Loading branch information
sonmezonur authored Nov 8, 2019
1 parent 3926ec7 commit 43633a3
Show file tree
Hide file tree
Showing 4 changed files with 246 additions and 167 deletions.
4 changes: 3 additions & 1 deletion _example/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ import (
type cfgType struct {
Key1 string `toml:"key1"`
Key2 string `toml:"key2"`
Port int `toml:"-" flag:"port" env:"port"`
Host string `toml:"host" flag:"server-host"`
Port int `toml:"-" flag:"port" env:"PORT"`
Secret string `env:"secret"`
}

Expand All @@ -30,6 +31,7 @@ func main() {

filename := flag.String("config", "test.toml", "Config filename")
flag.Int("port", 8080, "Port to listen on")
flag.String("server-host", "default", "Server host address")
flag.Parse()

var cfg cfgType
Expand Down
1 change: 1 addition & 0 deletions _example/test.toml
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
key1 = "123"
key2 = "454"
key3 = "key3val"
host = "localhost"
5 changes: 3 additions & 2 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
const (
envTag string = "env"
flagTag string = "flag"
tomlTag string = "toml"
)

// Load loads filepath into dst. It also handles "flag" binding.
Expand Down Expand Up @@ -89,8 +90,8 @@ func bindFlags(dst interface{}, metadata toml.MetaData) error {

useFlagDefaultValue := false
if !isFlagSet(tag) {
_, envHasKey := os.LookupEnv(tag)
if envHasKey || tomlHasKey(metadata, tag) {
_, envHasKey := os.LookupEnv(field.Tag(envTag))
if envHasKey || tomlHasKey(metadata, field.Tag(tomlTag)) {
continue
} else {
useFlagDefaultValue = true
Expand Down
Loading

0 comments on commit 43633a3

Please sign in to comment.