From 551d06fbe002c4d9a444db48b74d3ce47d780d08 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=98=99=E2=97=A6=20The=20Tablet=20=E2=9D=80=20GamerGirla?= =?UTF-8?q?ndCo=20=E2=97=A6=E2=9D=A7?= Date: Thu, 12 Sep 2024 17:15:04 -0400 Subject: [PATCH] update getNested utility to better handle slice fields --- util.go | 33 +++++++++++++++++++++++++++------ 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/util.go b/util.go index cd0ce1a..7fd5f27 100644 --- a/util.go +++ b/util.go @@ -54,19 +54,40 @@ func coerceInt(input reflect.Value, dst reflect.Value) interface{} { var arrRegex, _ = regexp.Compile(`\[(?P\d+)]$`) -func getNested(field string, value reflect.Value) (*reflect.StructField, *reflect.Value, error) { +func getNested(field string, aValue reflect.Value) (*reflect.Type, *reflect.Value, error) { if strings.HasPrefix(field, ".") || strings.HasSuffix(field, ".") { - return nil, nil, fmt.Errorf("Malformed field name %s passed", field) + return nil, nil, fmt.Errorf(errFmtMalformedField, field) } dots := strings.Split(field, ".") - if value.Kind() != reflect.Struct && arrRegex.FindString(dots[0]) == "" { - return nil, nil, fmt.Errorf("This value is not a struct!") + if value.Kind() != reflect.Struct /*&& arrRegex.FindString(dots[0]) == ""*/ { + if value.Kind() == reflect.Slice { + st := reflect.MakeSlice(value.Type().Elem(), 0, 0) + for i := 0; i < value.Len(); i++ { + cur := value.Index(i) + if len(dots) > 1 { + _, cv, _ := getNested(strings.Join(dots[1:], "."), cur.FieldByName(dots[0])) + reflect.Append(st, *cv) + //return getNested(, "."), fv) + } else { + reflect.Append(st, cur) + } + } + typ := st.Type().Elem() + return &typ, &st, nil + } + if len(dots) > 1 { + return nil, nil, ErrNotSliceOrStruct + } else { + return &aft, &value, nil + } + /*ft := value.Type() + */ } ref := value if ref.Kind() == reflect.Pointer { ref = ref.Elem() } - var fv reflect.Value = ref.FieldByName(arrRegex.ReplaceAllString(dots[0], "")) + var fv = ref.FieldByName(arrRegex.ReplaceAllString(dots[0], "")) if arrRegex.FindString(dots[0]) != "" && fv.Kind() == reflect.Slice { matches := arrRegex.FindStringSubmatch(dots[0]) ridx, _ := strconv.Atoi(matches[0]) @@ -78,7 +99,7 @@ func getNested(field string, value reflect.Value) (*reflect.StructField, *reflec if len(dots) > 1 { return getNested(strings.Join(dots[1:], "."), fv) } else { - return &ft, &fv, nil + return &ft.Type, &fv, nil } } func makeSettable(rval reflect.Value, value interface{}) reflect.Value {