From c58859d8f832459132a7e7b219d073b59414aa79 Mon Sep 17 00:00:00 2001 From: Inhere Date: Mon, 16 Oct 2023 10:12:14 +0800 Subject: [PATCH] :sparkles: feat: parse env var support required checking. see #156 --- issues_test.go | 45 +++++++++++++++++++++++++++++++++++++++++++++ util.go | 7 ++++++- 2 files changed, 51 insertions(+), 1 deletion(-) diff --git a/issues_test.go b/issues_test.go index 9390d00..7133d8c 100644 --- a/issues_test.go +++ b/issues_test.go @@ -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 @@ -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 { diff --git a/util.go b/util.go index 4da3a0d..f4472c0 100644 --- a/util.go +++ b/util.go @@ -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