Skip to content

Commit

Permalink
Added array support for env variables. Fix #6
Browse files Browse the repository at this point in the history
  • Loading branch information
serdarkalayci committed Dec 28, 2021
1 parent f6efe78 commit 6c1eb82
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 1 deletion.
7 changes: 7 additions & 0 deletions gonfig.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package gonfig
import (
"errors"
"os"
"strings"
)

type loadedSource struct {
Expand Down Expand Up @@ -49,6 +50,12 @@ func (c Configuration) findKey(key string) (interface{}, bool) {
case "env":
if val, fnd := os.LookupEnv(key); fnd {
value = val
if strings.HasPrefix(val, "[") && strings.HasSuffix(val, "]") { // We will assume the returned val is an array if it starts with "[" and ends with "]"
val = strings.TrimPrefix(val, "[")
val = strings.TrimSuffix(val, "]")
varr := strings.Split(val, ",")
value = varr
}
found = fnd
}
}
Expand Down
8 changes: 7 additions & 1 deletion gonfig_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,13 +80,19 @@ func Test_AddConfigSource_Env(t *testing.T) {
c = c.AddConfigSource(s)
assert.Equal(t, len(c.sources), 1)
os.Setenv("key1", "value1")
// Let's try to find a key that's there
val, found := c.findKey("key1")
assert.Equal(t, true, found)
assert.Equal(t, "value1", val)
// Let's try to find
// Let's try to find a key that's not there
val, found = c.findKey("key2")
assert.Equal(t, false, found)
assert.Nil(t, val)
os.Setenv("arrkey1", "[\"val1\",\"val2\",\"val3\"]")
// Let's try to find a key that's there
val, found = c.findKey("arrkey1")
assert.Equal(t, true, found)
assert.Equal(t, []string{"\"val1\"", "\"val2\"", "\"val3\""}, val)
}

func Test_GetInt(t *testing.T) {
Expand Down

0 comments on commit 6c1eb82

Please sign in to comment.