Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix:generic struct2MapAll #822

Merged
merged 5 commits into from
Oct 31, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 14 additions & 5 deletions filter/filter_impl/generic_filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"context"
"reflect"
"strings"
"time"
)

import (
Expand Down Expand Up @@ -93,13 +94,21 @@ func struct2MapAll(obj interface{}) interface{} {
if t.Kind() == reflect.Struct {
result := make(map[string]interface{}, t.NumField())
for i := 0; i < t.NumField(); i++ {
if v.Field(i).Kind() == reflect.Struct || v.Field(i).Kind() == reflect.Slice || v.Field(i).Kind() == reflect.Map {
if v.Field(i).CanInterface() {
setInMap(result, t.Field(i), struct2MapAll(v.Field(i).Interface()))
field := t.Field(i)
value := v.Field(i)
kind := value.Kind()
if kind == reflect.Struct || kind == reflect.Slice || kind == reflect.Map {
if value.CanInterface() {
tmp := value.Interface()
if _, ok := tmp.(time.Time); ok {
setInMap(result, field, tmp)
continue
}
setInMap(result, field, struct2MapAll(tmp))
}
} else {
if v.Field(i).CanInterface() {
setInMap(result, t.Field(i), v.Field(i).Interface())
if value.CanInterface() {
setInMap(result, field, value.Interface())
}
}
}
Expand Down
7 changes: 7 additions & 0 deletions filter/filter_impl/generic_filter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ package filter_impl
import (
"reflect"
"testing"
"time"
)

import (
Expand All @@ -38,13 +39,17 @@ func TestStruct2MapAll(t *testing.T) {
Xx string `m:"xx"`
} `m:"xxYy"`
} `m:"caCa"`
DaDa time.Time
EeEe int
}
testData.AaAa = "1"
testData.BaBa = "1"
testData.CaCa.BaBa = "2"
testData.CaCa.AaAa = "2"
testData.CaCa.XxYy.xxXx = "3"
testData.CaCa.XxYy.Xx = "3"
testData.DaDa = time.Date(2020, 10, 29, 2, 34, 0, 0, time.Local)
testData.EeEe = 100
m := struct2MapAll(testData).(map[string]interface{})
assert.Equal(t, "1", m["aaAa"].(string))
assert.Equal(t, "1", m["baBa"].(string))
Expand All @@ -53,6 +58,8 @@ func TestStruct2MapAll(t *testing.T) {

assert.Equal(t, reflect.Map, reflect.TypeOf(m["caCa"]).Kind())
assert.Equal(t, reflect.Map, reflect.TypeOf(m["caCa"].(map[string]interface{})["xxYy"]).Kind())
assert.Equal(t, "2020-10-29 02:34:00", m["daDa"].(time.Time).Format("2006-01-02 15:04:05"))
assert.Equal(t, 100, m["eeEe"].(int))
}

type testStruct struct {
Expand Down