From 51fcea28e3ef8639a05f71e0b170df210ce66e82 Mon Sep 17 00:00:00 2001 From: Yasss Date: Thu, 25 Apr 2019 19:16:51 +0200 Subject: [PATCH] Add optional parameter for file backend --- backend/file/file.go | 18 +++++++++++++----- backend/file/file_test.go | 16 ++++++++++++---- 2 files changed, 25 insertions(+), 9 deletions(-) diff --git a/backend/file/file.go b/backend/file/file.go index 351a8d3..b43dbaa 100644 --- a/backend/file/file.go +++ b/backend/file/file.go @@ -3,6 +3,7 @@ package file import ( "context" "encoding/json" + "fmt" "os" "path/filepath" @@ -14,21 +15,24 @@ import ( // Backend that loads a configuration from a file. // It supports json and yaml formats. type Backend struct { - path string - name string + path string + name string + optional bool } // NewBackend creates a configuration loader that loads from a file. // The content will get decoded based on the file extension. -func NewBackend(path string) *Backend { +// If optional parameter is set to true, calling Unmarshal won't return an error if the file doesn't exist. +func NewBackend(path string, optional bool) *Backend { name := filepath.Ext(path) if name != "" { name = name[1:] } return &Backend{ - path: path, - name: name, + path: path, + name: name, + optional: optional, } } @@ -37,6 +41,10 @@ func NewBackend(path string) *Backend { func (b *Backend) Unmarshal(ctx context.Context, to interface{}) error { f, err := os.Open(b.path) if err != nil { + if b.optional { + fmt.Printf("failed to open file at path \"%s\": %s\n", b.path, err.Error()) + return nil + } return errors.Wrapf(err, "failed to open file at path \"%s\"", b.path) } defer f.Close() diff --git a/backend/file/file_test.go b/backend/file/file_test.go index dcced62..e26caf2 100644 --- a/backend/file/file_test.go +++ b/backend/file/file_test.go @@ -41,7 +41,7 @@ func TestFileBackend(t *testing.T) { testLoad := func(t *testing.T, path string) { var c config - b := file.NewBackend(path) + b := file.NewBackend(path, false) err := b.Unmarshal(context.Background(), &c) require.NoError(t, err) @@ -90,17 +90,25 @@ timeout = 10 defer cleanup() var c config - b := file.NewBackend(path) + b := file.NewBackend(path, false) err := b.Unmarshal(context.Background(), &c) require.Error(t, err) }) - t.Run("File not found", func(t *testing.T) { + t.Run("Required file not found", func(t *testing.T) { var c config - b := file.NewBackend("some path") + b := file.NewBackend("some path", false) err := b.Unmarshal(context.Background(), &c) require.Error(t, err) }) + + t.Run("Optional file not found", func(t *testing.T) { + var c config + b := file.NewBackend("some path", true) + + err := b.Unmarshal(context.Background(), &c) + require.NoError(t, err) + }) }