Skip to content

Commit

Permalink
Merge pull request #52 from antonmashko/feat/default-value-on-no-var-…
Browse files Browse the repository at this point in the history
…injection

feat: return no value on injection missing env var
  • Loading branch information
antonmashko authored Oct 17, 2023
2 parents c1af813 + 82efb44 commit 42f354d
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 1 deletion.
6 changes: 5 additions & 1 deletion config_field.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,11 @@ func (s *externalSource) Value() (interface{}, option.ConfigSource) {
str, cs = envInjF(str)
switch cs {
case option.EnvVariable:
return (&envSource{name: str}).Value()
v, cs = (&envSource{name: str}).Value()
if cs == option.NoConfigValue {
return nil, option.NoConfigValue
}
return v, option.EnvVariable
default:
return v, option.ExternalSource
}
Expand Down
55 changes: 55 additions & 0 deletions external/external_json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,35 @@ func TestJsonConfig_IncorrectType_Err(t *testing.T) {
}
}

func TestJsonConfig_NilPointerNilInterface_Ok(t *testing.T) {
json := `{"foo":null,"bar":null}`
tc := struct {
Foo *string `json:"foo"`
Bar interface{} `json:"bar"`
}{}
if err := envconf.Parse(&tc, option.WithExternal(jsonconf.Json([]byte(json)))); err != nil {
t.Errorf("expected error but got nil")
}
if tc.Foo != nil || tc.Bar != nil {
t.Fatalf("unexpected result. expected nil got %v", tc)
}
}

func TestJsonConfig_NilPointerStruct_Ok(t *testing.T) {
json := `{"foo":null}`
tc := struct {
Foo *struct {
Bar string `json:"bar"`
} `json:"foo"`
}{}
if err := envconf.Parse(&tc, option.WithExternal(jsonconf.Json([]byte(json)))); err != nil {
t.Errorf("expected error but got nil")
}
if tc.Foo != nil {
t.Fatalf("unexpected result. expected nil got %v", *tc.Foo)
}
}

func TestJsonConfig_Array_Ok(t *testing.T) {
json := `{"foo":[2, 3, 4, 5]}`
tc := struct {
Expand Down Expand Up @@ -347,6 +376,32 @@ func TestJsonConfig_EnvVarInjection_Ok(t *testing.T) {
}
}

func TestJsonConfig_InjectionWithoutEnvVarDefaultValue_Ok(t *testing.T) {
json := `{
"foo": {
"bar": "${.env.JSON_TEST_ENVVAR_INJECTION}"
}
}`
tc := struct {
Foo struct {
Bar string `json:"bar" default:"foo_bar"`
}
}{}

expectedValue := "foo_bar"
err := envconf.Parse(&tc,
option.WithExternal(jsonconf.Json([]byte(json))),
option.WithExternalInjection(),
)
if err != nil {
t.Fatalf("failed to external parse. err=%s", err)
}

if tc.Foo.Bar != expectedValue {
t.Fatalf("incorrect result. expected=%s actual=%s", expectedValue, tc.Foo.Bar)
}
}

func TestJsonConfig_EnvVarInjectionFromCollection_Ok(t *testing.T) {
json := `{
"foo": [{
Expand Down

0 comments on commit 42f354d

Please sign in to comment.