Skip to content

Commit 4cacc4d

Browse files
wanwusangzhisam.yang
andauthored
fix: the time.Duration type panics due to numerical values (#4944)
Co-authored-by: sam.yang <sam.yang@yijinin.com>
1 parent a99c14d commit 4cacc4d

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

core/mapping/unmarshaler.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -622,7 +622,11 @@ func (u *Unmarshaler) processFieldNotFromString(fieldType reflect.Type, value re
622622

623623
return u.fillSliceFromString(fieldType, value, mapValue, fullName)
624624
case valueKind == reflect.String && derefedFieldType == durationType:
625-
return fillDurationValue(fieldType, value, mapValue.(string))
625+
v, ok := mapValue.(string)
626+
if !ok {
627+
return fmt.Errorf("unexpected type %T, expected a string value for field %s", mapValue, fullName)
628+
}
629+
return fillDurationValue(fieldType, value, v)
626630
case valueKind == reflect.String && typeKind == reflect.Struct && u.implementsUnmarshaler(fieldType):
627631
return u.fillUnmarshalerStruct(fieldType, value, mapValue.(string))
628632
default:

core/mapping/unmarshaler_test.go

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313

1414
"github.com/google/uuid"
1515
"github.com/stretchr/testify/assert"
16+
1617
"github.com/zeromicro/go-zero/core/jsonx"
1718
"github.com/zeromicro/go-zero/core/stringx"
1819
)
@@ -203,6 +204,20 @@ func TestUnmarshalDuration(t *testing.T) {
203204
}
204205
}
205206

207+
func TestUnmarshalDurationUnexpectedError(t *testing.T) {
208+
type inner struct {
209+
Duration time.Duration `key:"duration"`
210+
}
211+
content := "{\"duration\": 1}"
212+
var m = map[string]any{}
213+
err := jsonx.Unmarshal([]byte(content), &m)
214+
assert.NoError(t, err)
215+
var in inner
216+
err = UnmarshalKey(m, &in)
217+
assert.Error(t, err)
218+
assert.Contains(t, err.Error(), "unexpected type")
219+
}
220+
206221
func TestUnmarshalDurationDefault(t *testing.T) {
207222
type inner struct {
208223
Int int `key:"int"`

0 commit comments

Comments
 (0)