From 727e67fa5ba014b2ef3bf1c04015bf895164cce8 Mon Sep 17 00:00:00 2001 From: Jay Date: Thu, 13 Dec 2018 14:13:32 +0800 Subject: [PATCH] upgrade utils.ToMap --- model/commands.go | 2 +- module/utils/utils.go | 41 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/model/commands.go b/model/commands.go index 88dd0ee..937ff5d 100644 --- a/model/commands.go +++ b/model/commands.go @@ -18,7 +18,7 @@ type Commands struct { // CommandsWithGroup - type CommandsWithGroup struct { - Commands + Commands `cc:"-,<<"` GroupName string `db:"group_name" cc:"group_name"` } diff --git a/module/utils/utils.go b/module/utils/utils.go index 937282e..b84a83e 100644 --- a/module/utils/utils.go +++ b/module/utils/utils.go @@ -67,9 +67,48 @@ func ToMap(ss interface{}) map[string]interface{} { tag := string(t.Type().Field(i).Tag) str := mtag.FindStringSubmatch(tag) name := t.Type().Field(i).Name + leveling := false if len(str) > 1 { - name = str[1] + strArr := strings.Split(str[1], ",") + name = strArr[0] + if len(strArr) > 1 && strArr[1] == "<<" { + leveling = true + } } + + if f.Kind() == reflect.Slice { + if name == "-" { + continue + } + if f.Len() > 0 && f.Index(0).Kind() != reflect.Struct { + smap[name] = f.Interface() + continue + } + + tmp := make([]map[string]interface{}, f.Len()) + for i := 0; i < f.Len(); i++ { + tmp[i] = ToMap(f.Index(i).Interface()) + } + smap[name] = tmp + continue + } + + if f.Kind() == reflect.Struct { + if name == "-" && leveling == false { + continue + } + + tmp := ToMap(f.Interface()) + if leveling == true { + for k, v := range tmp { + smap[k] = v + } + } else if name != "-" && leveling == false { + smap[name] = tmp + } + continue + } + if name != "-" { smap[name] = f.Interface() }