Skip to content

Commit

Permalink
backend/env: treat empty environment variables as not found (#78)
Browse files Browse the repository at this point in the history
It's very unusual to distinguish between an environment variable
that's unset and one that's empty. When a value is required, looking
for a non-empty environment variable feels more correct.

As a recent example, the kafka-go config contained a "required" entry
for `KAFKA_ADDRS` which was satisfied by an empty environment
variable.
  • Loading branch information
rogpeppe committed Nov 20, 2019
1 parent 86d03df commit ec7d80e
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 8 deletions.
9 changes: 2 additions & 7 deletions backend/env/env.go
Expand Up @@ -13,18 +13,13 @@ import (
// lowercase letters to uppercase.
func NewBackend() backend.Backend {
return backend.Func("env", func(ctx context.Context, key string) ([]byte, error) {
val, ok := os.LookupEnv(key)
if ok {
if val := os.Getenv(key); val != "" {
return []byte(val), nil
}

key = strings.Replace(strings.ToUpper(key), "-", "_", -1)

val, ok = os.LookupEnv(key)
if ok {
if val := os.Getenv(key); val != "" {
return []byte(val), nil
}

return nil, backend.ErrNotFound
})
}
10 changes: 9 additions & 1 deletion backend/env/env_test.go
Expand Up @@ -10,11 +10,19 @@ import (
)

func TestEnvBackend(t *testing.T) {
t.Run("NotFound", func(t *testing.T) {
t.Run("NotFoundBecauseUnset", func(t *testing.T) {
b := NewBackend()

_, err := b.Get(context.Background(), "something that doesn't exist")
require.Equal(t, backend.ErrNotFound, err)

})

t.Run("NotFoundBecauseEmpty", func(t *testing.T) {
b := NewBackend()
os.Setenv("TESTCONFIG", "")
_, err := b.Get(context.Background(), "TESTCONFIG")
require.Equal(t, backend.ErrNotFound, err)
})

t.Run("ExactMatch", func(t *testing.T) {
Expand Down

0 comments on commit ec7d80e

Please sign in to comment.