From 08b995e1698f6e2b548a523c067b3b9048ea8bdd Mon Sep 17 00:00:00 2001 From: Inhere Date: Sat, 11 Feb 2023 19:16:57 +0800 Subject: [PATCH] :necktie: up: enhance support slice with ParseDefault and ParseEnv. fix: #114 --- issues_test.go | 25 +++++++++++++++++++++++++ load.go | 10 +++++++--- 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/issues_test.go b/issues_test.go index 73cce71..e208a32 100644 --- a/issues_test.go +++ b/issues_test.go @@ -282,3 +282,28 @@ func TestIssues_96(t *testing.T) { is.NotEmpty(c.Data()) is.Eq([]string{"Test1", "Test2"}, c.Get("parent.child")) } + +// https://github.com/gookit/config/issues/114 +func TestIssues_114(t *testing.T) { + c := config.NewWithOptions("test", + config.ParseDefault, + config.ParseEnv, + config.Readonly, + ) + + type conf struct { + Name string `mapstructure:"name" default:"${NAME | Bob}"` + Value []string `mapstructure:"value" default:"${VAL | val1}"` + } + + err := c.LoadExists("") + assert.NoErr(t, err) + + var cc conf + err = c.Decode(&cc) + assert.NoErr(t, err) + + assert.Eq(t, "Bob", cc.Name) + assert.Eq(t, []string{"val1"}, cc.Value) + // dump.Println(cc) +} diff --git a/load.go b/load.go index c0a914f..7fe3e18 100644 --- a/load.go +++ b/load.go @@ -4,7 +4,7 @@ import ( "errors" "flag" "fmt" - "io/ioutil" + "io" "net/http" "os" "path/filepath" @@ -42,6 +42,10 @@ func LoadExists(sourceFiles ...string) error { return dc.LoadExists(sourceFiles. // LoadExists load and parse config files, but will ignore not exists file. func (c *Config) LoadExists(sourceFiles ...string) (err error) { for _, file := range sourceFiles { + if file == "" { + continue + } + if err = c.loadFile(file, true, ""); err != nil { return } @@ -72,7 +76,7 @@ func (c *Config) LoadRemote(format, url string) (err error) { } // read response content - bts, err := ioutil.ReadAll(resp.Body) + bts, err := io.ReadAll(resp.Body) if err == nil { if err = c.parseSourceCode(format, bts); err != nil { return @@ -386,7 +390,7 @@ func (c *Config) loadFile(file string, loadExist bool, format string) (err error defer fd.Close() // read file content - bts, err := ioutil.ReadAll(fd) + bts, err := io.ReadAll(fd) if err == nil { // get format for file ext if format == "" {