From 142c46228b7509e6350b4554b05af468a9594411 Mon Sep 17 00:00:00 2001 From: MarkJoyMa Date: Thu, 2 Mar 2023 21:47:07 +0800 Subject: [PATCH] x --- core/conf/config.go | 3 ++- core/conf/config_test.go | 12 ++++++++++++ core/mapping/unmarshaler.go | 9 ++++++++- core/mapping/unmarshaler_test.go | 12 ++++++++++++ 4 files changed, 34 insertions(+), 2 deletions(-) diff --git a/core/conf/config.go b/core/conf/config.go index 170c6c14..d53a79d6 100644 --- a/core/conf/config.go +++ b/core/conf/config.go @@ -32,7 +32,8 @@ type fieldInfo struct { mapField *fieldInfo } -// FillDefault fills the default values for the given v. +// FillDefault fills the default values for the given v, +// and the premise is that the value of v must be guaranteed to be empty func FillDefault(v any) error { return fillDefaultUnmarshaler.Unmarshal(map[string]any{}, v) } diff --git a/core/conf/config_test.go b/core/conf/config_test.go index 33785db5..8dba474f 100644 --- a/core/conf/config_test.go +++ b/core/conf/config_test.go @@ -1078,4 +1078,16 @@ func TestFillDefaultUnmarshal(t *testing.T) { assert.Equal(t, st.A, "a") assert.Equal(t, st.C, "c") }) + + t.Run("has vaue", func(t *testing.T) { + type St struct { + A string `json:",default=a"` + B string + } + var st = St{ + A: "b", + } + err := FillDefault(&st) + assert.Error(t, err) + }) } diff --git a/core/mapping/unmarshaler.go b/core/mapping/unmarshaler.go index 5f3061d2..fe638ce1 100644 --- a/core/mapping/unmarshaler.go +++ b/core/mapping/unmarshaler.go @@ -711,7 +711,14 @@ func (u *Unmarshaler) processNamedField(field reflect.StructField, value reflect valuer := createValuer(m, opts) mapValue, hasValue := getValue(valuer, canonicalKey) - if !hasValue || u.opts.fillDefault { + + // When fillDefault is used, m is a null value, hasValue must be false, all priority judgments fillDefault, + if u.opts.fillDefault { + if !value.IsZero() { + return fmt.Errorf("set the default value, %s must be zero", fullName) + } + return u.processNamedFieldWithoutValue(field.Type, value, opts, fullName) + } else if !hasValue { return u.processNamedFieldWithoutValue(field.Type, value, opts, fullName) } diff --git a/core/mapping/unmarshaler_test.go b/core/mapping/unmarshaler_test.go index 0c50d269..d2e6fc09 100644 --- a/core/mapping/unmarshaler_test.go +++ b/core/mapping/unmarshaler_test.go @@ -4425,4 +4425,16 @@ func TestFillDefaultUnmarshal(t *testing.T) { assert.Equal(t, st.A, "a") assert.Equal(t, st.C, "c") }) + + t.Run("has value", func(t *testing.T) { + type St struct { + A string `json:",default=a"` + B string + } + var st = St{ + A: "b", + } + err := fillDefaultUnmarshal.Unmarshal(map[string]any{}, &st) + assert.Error(t, err) + }) }