Skip to content

Commit 1b0dacd

Browse files
committed
fix(os/gstructs): strip tag options in TagPriorityName to avoid field name pollution
TagPriorityName() returned raw tag values including options like ",omitempty", causing RuleFuncInput.Field to be "user_name,omitempty" instead of "user_name". Now splits on comma and takes only the name part, consistent with structcache.genPriorityTagAndFieldName(). closes gogf#4665
1 parent c8a11f7 commit 1b0dacd

2 files changed

Lines changed: 34 additions & 2 deletions

File tree

os/gstructs/gstructs_field_tag.go

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -101,8 +101,12 @@ func (f *Field) TagPriorityName() string {
101101
name := f.Name()
102102
for _, tagName := range gtag.StructTagPriority {
103103
if tagValue := f.Tag(tagName); tagValue != "" {
104-
name = tagValue
105-
break
104+
// Strip tag options after comma, e.g., json:"name,omitempty" -> "name".
105+
tagValue = strings.Split(tagValue, ",")[0]
106+
if tagValue != "" {
107+
name = tagValue
108+
break
109+
}
106110
}
107111
}
108112
return name

os/gstructs/gstructs_z_unit_test.go

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -546,4 +546,32 @@ func Test_Fields_TagPriorityName(t *testing.T) {
546546
t.Assert(fields[2].TagPriorityName(), "pass_json")
547547
t.Assert(fields[3].TagPriorityName(), "IsMen")
548548
})
549+
// Tag with omitempty option should return name only, not "name,omitempty".
550+
gtest.C(t, func(t *gtest.T) {
551+
type User struct {
552+
Name string `json:"user_name,omitempty"`
553+
Age uint `gconv:"age,string" json:"age_json"`
554+
}
555+
var user *User
556+
fields, _ := gstructs.Fields(gstructs.FieldsInput{
557+
Pointer: user,
558+
RecursiveOption: 0,
559+
})
560+
t.Assert(fields[0].TagPriorityName(), "user_name")
561+
t.Assert(fields[1].TagPriorityName(), "age")
562+
})
563+
// Empty tag name with options (e.g., gconv:",omitempty") should fallthrough to next priority tag.
564+
gtest.C(t, func(t *gtest.T) {
565+
type User struct {
566+
Name string `gconv:",omitempty" json:"name_json"`
567+
Age uint `gconv:",string" param:",omitempty" json:"age_json"`
568+
}
569+
var user *User
570+
fields, _ := gstructs.Fields(gstructs.FieldsInput{
571+
Pointer: user,
572+
RecursiveOption: 0,
573+
})
574+
t.Assert(fields[0].TagPriorityName(), "name_json")
575+
t.Assert(fields[1].TagPriorityName(), "age_json")
576+
})
549577
}

0 commit comments

Comments
 (0)