From f887c9f44b867074df0fc65363eb894069e8a384 Mon Sep 17 00:00:00 2001 From: John Guo Date: Tue, 12 Oct 2021 17:52:31 +0800 Subject: [PATCH] improve package gmeta --- protocol/goai/goai_path.go | 6 +----- util/gconv/gconv_map.go | 5 +++++ util/gmeta/gmeta_unit_test.go | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 41 insertions(+), 5 deletions(-) diff --git a/protocol/goai/goai_path.go b/protocol/goai/goai_path.go index 404930cad..46b890044 100644 --- a/protocol/goai/goai_path.go +++ b/protocol/goai/goai_path.go @@ -277,9 +277,5 @@ func (oai *OpenApiV3) addPath(in addPathInput) error { } func (oai *OpenApiV3) doesStructHasNoFields(s interface{}) bool { - structFields, _ := structs.Fields(structs.FieldsInput{ - Pointer: s, - RecursiveOption: structs.RecursiveOptionEmbeddedNoTag, - }) - return len(structFields) == 0 + return reflect.TypeOf(s).NumField() == 0 } diff --git a/util/gconv/gconv_map.go b/util/gconv/gconv_map.go index 9ad0a5cb5..811153499 100644 --- a/util/gconv/gconv_map.go +++ b/util/gconv/gconv_map.go @@ -282,6 +282,11 @@ func doMapConvertForMapOrStructValue(isRoot bool, value interface{}, recursive b } switch rvAttrKind { case reflect.Struct: + // Embedded struct and has no fields, just ignores it. + // Eg: gmeta.Meta + if rvAttrField.Type().NumField() == 0 { + continue + } var ( hasNoTag = mapKey == fieldName rvAttrInterface = rvAttrField.Interface() diff --git a/util/gmeta/gmeta_unit_test.go b/util/gmeta/gmeta_unit_test.go index 630c6e451..db167b2b4 100644 --- a/util/gmeta/gmeta_unit_test.go +++ b/util/gmeta/gmeta_unit_test.go @@ -8,6 +8,7 @@ package gmeta_test import ( "github.com/gogf/gf/v2/internal/json" + "github.com/gogf/gf/v2/util/gconv" "github.com/gogf/gf/v2/util/gmeta" "testing" @@ -36,3 +37,37 @@ func TestMeta_Basic(t *testing.T) { t.Assert(b, `{"Id":100,"Name":"john"}`) }) } + +func TestMeta_Convert_Map(t *testing.T) { + type A struct { + gmeta.Meta `tag:"123" orm:"456"` + Id int + Name string + } + + gtest.C(t, func(t *gtest.T) { + a := &A{ + Id: 100, + Name: "john", + } + m := gconv.Map(a) + t.Assert(len(m), 2) + t.Assert(m[`Meta`], nil) + }) +} + +func TestMeta_Json(t *testing.T) { + type A struct { + gmeta.Meta `tag:"123" orm:"456"` + Id int + } + + gtest.C(t, func(t *gtest.T) { + a := &A{ + Id: 100, + } + b, err := json.Marshal(a) + t.AssertNil(err) + t.Assert(string(b), `{"Id":100}`) + }) +}