Skip to content

Commit

Permalink
support loading config from io.Reader
Browse files Browse the repository at this point in the history
  • Loading branch information
alovak committed May 10, 2021
1 parent f07f3d9 commit 1f7f7dc
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 2 deletions.
23 changes: 21 additions & 2 deletions config/config.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package config

import (
"fmt"
"io"
"os"
"strings"

Expand All @@ -25,7 +27,7 @@ func NewService(logger log.Logger) Service {

func (s *Service) Load(config interface{}) error {
if err := s.LoadFile(pkger.Include("/configs/config.default.yml"), config); err != nil {
return err
s.logger.LogErrorf("loading default config file using pkger: %w", err)
}

if err := LoadEnvironmentFile(s.logger, APP_CONFIG, config); err != nil {
Expand All @@ -45,12 +47,29 @@ func (s *Service) LoadFile(file string, config interface{}) error {

f, err := pkger.Open(file)
if err != nil {
return logger.LogErrorf("pkger unable to load %s: %w", file, err).Err()
return fmt.Errorf("pkger unable to load %s: %w", file, err)
}

deflt := viper.New()
deflt.SetConfigType("yaml")
if err := deflt.ReadConfig(f); err != nil {
return fmt.Errorf("unable to load the defaults: %w", err)
}

if err := deflt.Unmarshal(config); err != nil {
return fmt.Errorf("unable to unmarshal the defaults: %w", err)
}

return nil
}

func (s *Service) LoadFromReader(in io.Reader, config interface{}) error {
logger := s.logger
logger.Info().Logf("loading config file from reader")

deflt := viper.New()
deflt.SetConfigType("yaml")
if err := deflt.ReadConfig(in); err != nil {
return logger.LogErrorf("unable to load the defaults: %w", err).Err()
}

Expand Down
19 changes: 19 additions & 0 deletions config/config_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package config_test

import (
"embed"
"os"
"testing"

Expand All @@ -17,6 +18,7 @@ type ConfigModel struct {
Default string
App string
Secret string
Custom string
}

func Test_Load(t *testing.T) {
Expand All @@ -37,3 +39,20 @@ func Test_Load(t *testing.T) {
require.Equal(t, "app", cfg.Config.App)
require.Equal(t, "keep secret!", cfg.Config.Secret)
}

//go:embed testdata/*.yml
var configs embed.FS

func Test_LoadFile(t *testing.T) {
cfg := &GlobalConfigModel{}

service := config.NewService(log.NewDefaultLogger())

file, err := configs.Open("testdata/config.yml")
require.NoError(t, err)

err = service.LoadFromReader(file, cfg)
require.NoError(t, err)

require.Equal(t, "custom", cfg.Config.Custom)
}
2 changes: 2 additions & 0 deletions config/testdata/config.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Config:
Custom: "custom"

0 comments on commit 1f7f7dc

Please sign in to comment.