Commit 5281b952
5281b952d61cMerged
Svyatoslav Dumchenko <[email protected]> ยท 5 years ago ยท 2 files ยท ~2 modified
Description
Override hasKey template function
Details
- Commit
- 5281b952d61c
- Parent
- 02d66c9c46c7
pkg/template/extra.gomodifiedView file
@@ -242,3 +242,57 @@
242242
}243243
return Get(strings.Join(keys[1:], "."), v)244244
}245+
246+
func HasKey(path string, varArgs ...interface{}) (bool, error) {247+
var defSet bool248+
var def interface{}249+
var obj interface{}250+
switch len(varArgs) {251+
case 1:252+
defSet = false253+
def = nil254+
obj = varArgs[0]255+
case 2:256+
defSet = true257+
def = varArgs[0]258+
obj = varArgs[1]259+
default:260+
return false, fmt.Errorf("unexpected number of args pased to the template function get(path, [def, ]obj): expected 1 or 2, got %d, args was %v", len(varArgs), varArgs)261+
}262+
263+
if path == "" {264+
return true, nil265+
}266+
keys := strings.Split(path, ".")267+
var v interface{}268+
var ok bool269+
switch typedObj := obj.(type) {270+
case map[string]interface{}:271+
v, ok = typedObj[keys[0]]272+
if !ok {273+
return defSet, nil274+
}275+
case map[interface{}]interface{}:276+
v, ok = typedObj[keys[0]]277+
if !ok {278+
return defSet, nil279+
}280+
default:281+
maybeStruct := reflect.ValueOf(typedObj)282+
if maybeStruct.Kind() != reflect.Struct {283+
return false, &noValueError{fmt.Sprintf("unexpected type(%v) of value for key \"%s\": it must be either map[string]interface{} or any struct", reflect.TypeOf(obj), keys[0])}284+
} else if maybeStruct.NumField() < 1 {285+
return false, &noValueError{fmt.Sprintf("no accessible struct fields for key \"%s\"", keys[0])}286+
}287+
f := maybeStruct.FieldByName(keys[0])288+
if !f.IsValid() {289+
return defSet, nil290+
}291+
v = f.Interface()292+
}293+
294+
if defSet {295+
return HasKey(strings.Join(keys[1:], "."), def, v)296+
}297+
return HasKey(strings.Join(keys[1:], "."), v)298+
}pkg/template/func.gomodifiedView file
Loading diffโฆ