diff --git a/backend/simplemap/simplemap.go b/backend/simplemap/simplemap.go new file mode 100644 index 0000000..fec77d1 --- /dev/null +++ b/backend/simplemap/simplemap.go @@ -0,0 +1,44 @@ +package simplemap + +import ( + "github.com/heetch/confita" + "github.com/pkg/errors" + "reflect" + + "context" +) + +// Backend that loads config from map +type Backend struct { + theMap map[string]interface{} +} + +// NewBackend creates a simplemap backend. +func NewBackend(theMap map[string]interface{}) *Backend { + return &Backend{ + theMap: theMap, + } +} + +// LoadStruct takes a struct config and loads the map into it +func (b *Backend) LoadStruct(ctx context.Context, cfg *confita.StructConfig) error { + for _, f := range cfg.Fields { + mapVal := b.theMap[f.Key] + if mapVal == nil { + continue + } + mapRef := reflect.ValueOf(mapVal) + f.Value.Set(mapRef) + } + return nil +} + +// Get is not implemented. +func (b *Backend) Get(ctx context.Context, key string) ([]byte, error) { + return nil, errors.New("not implemented") +} + +// Name returns the name of the flags backend. +func (b *Backend) Name() string { + return "simplemap" +} diff --git a/backend/simplemap/simplemap_test.go b/backend/simplemap/simplemap_test.go new file mode 100644 index 0000000..6a444f4 --- /dev/null +++ b/backend/simplemap/simplemap_test.go @@ -0,0 +1,39 @@ +package simplemap_test + +import ( + "context" + "github.com/heetch/confita" + "github.com/heetch/confita/backend/simplemap" + "github.com/stretchr/testify/require" + "testing" + "time" +) + +func TestSimplemapBackend(t *testing.T) { + type config struct { + Name string `config:"Name"` + Age int `config:"Age"` + Negative int `config:"Negative"` + Balance float64 `config:"Balance"` + Timeout time.Duration `config:"Timeout"` + } + + b := simplemap.NewBackend(map[string]interface{}{ + "Name": "Bob", + "Age": 30, + "Negative": -10, + "Balance": 1234.56, + "Timeout": 10 * time.Second, + }) + + var c config + require.Equal(t, "simplemap", b.Name()) + err := confita.NewLoader(b).Load(context.Background(), &c) + + require.NoError(t, err) + require.Equal(t, "Bob", c.Name) + require.Equal(t, 30, c.Age) + require.Equal(t, -10, c.Negative) + require.Equal(t, 1234.56, c.Balance) + require.Equal(t, 10*time.Second, c.Timeout) +}