diff --git a/pkg/tmpl/get_or_nil.go b/pkg/tmpl/get_or_nil.go index eaa0c94e..71a46085 100644 --- a/pkg/tmpl/get_or_nil.go +++ b/pkg/tmpl/get_or_nil.go @@ -50,6 +50,15 @@ func get(path string, varArgs ...interface{}) (interface{}, error) { } return nil, &noValueError{fmt.Sprintf("no value exist for key \"%s\" in %v", keys[0], typedObj)} } + case map[string]string: + v, ok = typedObj[keys[0]] + if !ok { + if defSet { + return def, nil + } + return nil, &noValueError{fmt.Sprintf("no value exist for key \"%s\" in %v", keys[0], typedObj)} + } + return v, nil case map[interface{}]interface{}: v, ok = typedObj[keys[0]] if !ok { diff --git a/pkg/tmpl/get_or_nil_test.go b/pkg/tmpl/get_or_nil_test.go index 54f30bdf..33226ff6 100644 --- a/pkg/tmpl/get_or_nil_test.go +++ b/pkg/tmpl/get_or_nil_test.go @@ -2,12 +2,37 @@ package tmpl import ( "testing" + + "github.com/stretchr/testify/require" ) type EmptyStruct struct { } -func TestGetStruct(t *testing.T) { +func TestComplexStruct(t *testing.T) { + type CS struct { + Bar map[string]string + } + obj := CS{ + Bar: map[string]string{ + "foo": "bar", + }, + } + + existValue, err := get("Bar.foo", obj) + require.NoErrorf(t, err, "unexpected error: %v", err) + require.Equalf(t, existValue, "bar", "unexpected value for path Bar.foo in %v: expected=bar, actual=%v", obj, existValue) + + noExistValue, err := get("Bar.baz", obj) + require.Errorf(t, err, "expected error but was not occurred") + require.Nilf(t, noExistValue, "expected nil but was not occurred") + + noExistValueWithDefault, err := get("Bar.baz", "default", obj) + require.NoErrorf(t, err, "unexpected error: %v", err) + require.Equalf(t, noExistValueWithDefault, "default", "unexpected value for path Bar.baz in %v: expected=default, actual=%v", obj, noExistValueWithDefault) +} + +func TestGetSimpleStruct(t *testing.T) { type Foo struct{ Bar string } obj := struct{ Foo }{Foo{Bar: "Bar"}}