From 27b47f976caf892137694151bda8363301bbeec0 Mon Sep 17 00:00:00 2001 From: wwqgtxx Date: Mon, 3 Nov 2025 14:57:23 +0800 Subject: [PATCH] chore: structure support ignore tag --- common/structure/structure.go | 6 ++++++ common/structure/structure_test.go | 20 ++++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/common/structure/structure.go b/common/structure/structure.go index 5bafc178..bf79f7dd 100644 --- a/common/structure/structure.go +++ b/common/structure/structure.go @@ -53,6 +53,12 @@ func (d *Decoder) Decode(src map[string]any, dst any) error { key, omitKey, found := strings.Cut(tag, ",") omitempty := found && omitKey == "omitempty" + // As a special case, if the field tag is "-", the field is always omitted. + // Note that a field with name "-" can still be generated using the tag "-,". + if key == "-" { + continue + } + value, ok := src[key] if !ok { if d.option.KeyReplacer != nil { diff --git a/common/structure/structure_test.go b/common/structure/structure_test.go index fcdd853a..06dffd0f 100644 --- a/common/structure/structure_test.go +++ b/common/structure/structure_test.go @@ -288,3 +288,23 @@ func TestStructure_Null(t *testing.T) { assert.Nil(t, err) assert.Equal(t, s.Opt.Bar, "") } + +func TestStructure_Ignore(t *testing.T) { + rawMap := map[string]any{ + "-": "newData", + } + + s := struct { + MustIgnore string `test:"-"` + }{MustIgnore: "oldData"} + + err := decoder.Decode(rawMap, &s) + assert.Nil(t, err) + assert.Equal(t, s.MustIgnore, "oldData") + + // test omitempty + delete(rawMap, "-") + err = decoder.Decode(rawMap, &s) + assert.Nil(t, err) + assert.Equal(t, s.MustIgnore, "oldData") +}