From 4cacc4d9d3eb8ebd1ecaef7018a6e0f7fb4468ea Mon Sep 17 00:00:00 2001 From: wanwu <609780590@qq.com> Date: Thu, 12 Jun 2025 23:11:07 +0800 Subject: [PATCH] fix: the time.Duration type panics due to numerical values (#4944) Co-authored-by: sam.yang --- core/mapping/unmarshaler.go | 6 +++++- core/mapping/unmarshaler_test.go | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/core/mapping/unmarshaler.go b/core/mapping/unmarshaler.go index 3ce016fc1..fb4838c22 100644 --- a/core/mapping/unmarshaler.go +++ b/core/mapping/unmarshaler.go @@ -622,7 +622,11 @@ func (u *Unmarshaler) processFieldNotFromString(fieldType reflect.Type, value re return u.fillSliceFromString(fieldType, value, mapValue, fullName) case valueKind == reflect.String && derefedFieldType == durationType: - return fillDurationValue(fieldType, value, mapValue.(string)) + v, ok := mapValue.(string) + if !ok { + return fmt.Errorf("unexpected type %T, expected a string value for field %s", mapValue, fullName) + } + return fillDurationValue(fieldType, value, v) case valueKind == reflect.String && typeKind == reflect.Struct && u.implementsUnmarshaler(fieldType): return u.fillUnmarshalerStruct(fieldType, value, mapValue.(string)) default: diff --git a/core/mapping/unmarshaler_test.go b/core/mapping/unmarshaler_test.go index d4a1a67f2..ac9efd8ba 100644 --- a/core/mapping/unmarshaler_test.go +++ b/core/mapping/unmarshaler_test.go @@ -13,6 +13,7 @@ import ( "github.com/google/uuid" "github.com/stretchr/testify/assert" + "github.com/zeromicro/go-zero/core/jsonx" "github.com/zeromicro/go-zero/core/stringx" ) @@ -203,6 +204,20 @@ func TestUnmarshalDuration(t *testing.T) { } } +func TestUnmarshalDurationUnexpectedError(t *testing.T) { + type inner struct { + Duration time.Duration `key:"duration"` + } + content := "{\"duration\": 1}" + var m = map[string]any{} + err := jsonx.Unmarshal([]byte(content), &m) + assert.NoError(t, err) + var in inner + err = UnmarshalKey(m, &in) + assert.Error(t, err) + assert.Contains(t, err.Error(), "unexpected type") +} + func TestUnmarshalDurationDefault(t *testing.T) { type inner struct { Int int `key:"int"`