From 5d15e1a50009bbe49c193cc57e110a2f88508926 Mon Sep 17 00:00:00 2001 From: "Frankee.zhou" Date: Sat, 27 Nov 2021 15:17:39 +0800 Subject: [PATCH] let gorm can scan protobuf struct without add an ignore tag ("-") manually link: https://github.com/go-gorm/gorm/issues/4877 --- schema/schema.go | 2 +- schema/schema_test.go | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/schema/schema.go b/schema/schema.go index eca113e9..3a66b967 100644 --- a/schema/schema.go +++ b/schema/schema.go @@ -155,7 +155,7 @@ func ParseWithSpecialTableName(dest interface{}, cacheStore *sync.Map, namer Nam } for i := 0; i < modelType.NumField(); i++ { - if fieldStruct := modelType.Field(i); ast.IsExported(fieldStruct.Name) { + if fieldStruct := modelType.Field(i); ast.IsExported(fieldStruct.Name) && fieldStruct.Tag.Get("json") != "-" { if field := schema.ParseField(fieldStruct); field.EmbeddedSchema != nil { schema.Fields = append(schema.Fields, field.EmbeddedSchema.Fields...) } else { diff --git a/schema/schema_test.go b/schema/schema_test.go index a426cd90..93dffd2c 100644 --- a/schema/schema_test.go +++ b/schema/schema_test.go @@ -297,3 +297,21 @@ func TestEmbeddedStructForCustomizedNamingStrategy(t *testing.T) { }) } } + +func TestParseProtobufStruct(t *testing.T) { + type Response struct { + Code *uint32 `protobuf:"varint,1,opt,name=code" json:"code,omitempty"` + XXX_NoUnkeyedLiteral struct{} `json:"-"` + XXX_unrecognized []byte `json:"-"` + XXX_sizecache int32 `json:"-"` + } + + responseSchema, err := schema.Parse(&Response{}, &sync.Map{}, CustomizedNamingStrategy{schema.NamingStrategy{}}) + if err != nil { + t.Fatalf("failed to parse protobuf struct, got error %v", err) + } + + if len(responseSchema.Fields) != 1 || responseSchema.Fields[0].Name != "Code" { + t.Errorf("schema %v do include private field in protobuf struct", responseSchema) + } +}