Skip to content

Commit

Permalink
✨ feat: parse env var support required checking. see #156
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Oct 16, 2023
1 parent 49ece93 commit c58859d
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
45 changes: 45 additions & 0 deletions issues_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -441,6 +441,7 @@ type DurationStruct struct {
Duration time.Duration
}

// https://github.com/gookit/config/pull/151
func TestDuration(t *testing.T) {
var (
err error
Expand All @@ -462,6 +463,50 @@ func TestDuration(t *testing.T) {
}
}

// https://github.com/gookit/config/issues/156
func TestIssues_156(t *testing.T) {
c := config.New("test", config.ParseEnv)
c.AddDriver(yaml.Driver)

type DbConfig struct {
Url string
Type string
Password string
Username string
}

err := c.LoadStrings(config.Yaml, `
---
datasource:
password: ${DATABASE_PASSWORD|?} # use fixed error message
type: postgres
username: ${DATABASE_USERNAME|postgres}
url: ${DATABASE_URL|?error message2}
`)
assert.NoErr(t, err)
// dump.Println(c.Data())
assert.NotEmpty(t, c.Sub("datasource"))

// will error
dbConf := &DbConfig{}
err = c.BindStruct("datasource", dbConf)
assert.Err(t, err)
assert.ErrSubMsg(t, err, "decoding 'Password': value is required for var: DATABASE_PASSWORD")
assert.ErrSubMsg(t, err, "error decoding 'Url': error message2")

testutil.MockEnvValues(map[string]string{
"DATABASE_PASSWORD": "1234yz56",
"DATABASE_URL": "localhost:5432/postgres?sslmode=disable",
}, func() {
dbConf := &DbConfig{}
err = c.BindStruct("datasource", dbConf)
assert.NoErr(t, err)
dump.Println(dbConf)
assert.Eq(t, "1234yz56", dbConf.Password)
assert.Eq(t, "localhost:5432/postgres?sslmode=disable", dbConf.Url)
})
}

// https://github.com/gookit/config/issues/162
func TestIssues_162(t *testing.T) {
type Logger struct {
Expand Down
7 changes: 6 additions & 1 deletion util.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,14 @@ func ValDecodeHookFunc(parseEnv, parseTime bool) mapstructure.DecodeHookFunc {
return data, nil
}

var err error
str := data.(string)
if parseEnv {
str = envutil.ParseEnvValue(str)
// https://docs.docker.com/compose/environment-variables/env-file/
str, err = envutil.ParseOrErr(str)
if err != nil {
return nil, err
}
}
if len(str) < 2 {
return str, nil
Expand Down

0 comments on commit c58859d

Please sign in to comment.