From a82fd19209bb8bb67f5ec56d25626d54d9a1012e Mon Sep 17 00:00:00 2001 From: Allenxuxu <120582243@qq.com> Date: Sun, 19 Jan 2020 16:31:02 +0800 Subject: [PATCH] handle Loader.Load return value error --- config/config.go | 4 ++-- config/default.go | 9 ++++++--- config/default_test.go | 23 +++++++++++++++++------ 3 files changed, 25 insertions(+), 11 deletions(-) diff --git a/config/config.go b/config/config.go index 020c71d5..b45215e8 100644 --- a/config/config.go +++ b/config/config.go @@ -43,11 +43,11 @@ type Option func(o *Options) var ( // Default Config Manager - DefaultConfig = NewConfig() + DefaultConfig, _ = NewConfig() ) // NewConfig returns new config -func NewConfig(opts ...Option) Config { +func NewConfig(opts ...Option) (Config, error) { return newConfig(opts...) } diff --git a/config/default.go b/config/default.go index c01da98c..09bccdc6 100644 --- a/config/default.go +++ b/config/default.go @@ -30,7 +30,7 @@ type watcher struct { value reader.Value } -func newConfig(opts ...Option) Config { +func newConfig(opts ...Option) (Config, error) { options := Options{ Loader: memory.NewLoader(), Reader: json.NewReader(), @@ -40,7 +40,10 @@ func newConfig(opts ...Option) Config { o(&options) } - options.Loader.Load(options.Source...) + if err := options.Loader.Load(options.Source...); err != nil { + return nil, err + } + snap, _ := options.Loader.Snapshot() vals, _ := options.Reader.Values(snap.ChangeSet) @@ -53,7 +56,7 @@ func newConfig(opts ...Option) Config { go c.run() - return c + return c, nil } func (c *config) run() { diff --git a/config/default_test.go b/config/default_test.go index b2ef0575..e53a877b 100644 --- a/config/default_test.go +++ b/config/default_test.go @@ -55,7 +55,10 @@ func TestConfigLoadWithGoodFile(t *testing.T) { }() // Create new config - conf := NewConfig() + conf, err := NewConfig() + if err != nil { + t.Fatalf("Expected no error but got %v", err) + } // Load file source if err := conf.Load(file.NewSource( file.WithPath(path), @@ -73,9 +76,12 @@ func TestConfigLoadWithInvalidFile(t *testing.T) { }() // Create new config - conf := NewConfig() + conf, err := NewConfig() + if err != nil { + t.Fatalf("Expected no error but got %v", err) + } // Load file source - err := conf.Load(file.NewSource( + err = conf.Load(file.NewSource( file.WithPath(path), file.WithPath("/i/do/not/exists.json"), )) @@ -105,13 +111,18 @@ func TestConfigMerge(t *testing.T) { }() os.Setenv("AMQP_HOST", "rabbit.testing.com") - conf := NewConfig() - conf.Load( + conf, err := NewConfig() + if err != nil { + t.Fatalf("Expected no error but got %v", err) + } + if err := conf.Load( file.NewSource( file.WithPath(path), ), env.NewSource(), - ) + ); err != nil { + t.Fatalf("Expected no error but got %v", err) + } actualHost := conf.Get("amqp", "host").String("backup") if actualHost != "rabbit.testing.com" {