From 84f9863b6390a27cb7cdc44ef6fb7e3f7c09d5c8 Mon Sep 17 00:00:00 2001 From: Mikael <13247629622@163.com> Date: Sun, 12 Feb 2023 19:53:20 +0800 Subject: [PATCH] only unmashal public variables (#2872) * only unmashal public variables * only unmashal public variables * only unmashal public variables * only unmashal public variables --- core/mapping/unmarshaler.go | 3 +++ core/mapping/unmarshaler_test.go | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/core/mapping/unmarshaler.go b/core/mapping/unmarshaler.go index 5dd18f65..b3543d79 100644 --- a/core/mapping/unmarshaler.go +++ b/core/mapping/unmarshaler.go @@ -853,6 +853,9 @@ func (u *Unmarshaler) unmarshalWithFullName(m valuerWithParent, v any, fullName numFields := baseType.NumField() for i := 0; i < numFields; i++ { + if !baseType.Field(i).IsExported() { + continue + } if err := u.processField(baseType.Field(i), valElem.Field(i), m, fullName); err != nil { return err } diff --git a/core/mapping/unmarshaler_test.go b/core/mapping/unmarshaler_test.go index ab0d6a42..4d9dd98b 100644 --- a/core/mapping/unmarshaler_test.go +++ b/core/mapping/unmarshaler_test.go @@ -4265,6 +4265,24 @@ func TestUnmarshalStructPtrOfPtr(t *testing.T) { } } +func TestUnmarshalOnlyPublicVariables(t *testing.T) { + type demo struct { + age int `key:"age"` + Name string `key:"name"` + } + + m := map[string]any{ + "age": 3, + "name": "go-zero", + } + + var in demo + if assert.NoError(t, UnmarshalKey(m, &in)) { + assert.Equal(t, 0, in.age) + assert.Equal(t, "go-zero", in.Name) + } +} + func BenchmarkDefaultValue(b *testing.B) { for i := 0; i < b.N; i++ { var a struct {