fix: panic when decoding time.Time with context

close #327
This commit is contained in:
Nao Yonashiro 2022-01-26 01:02:27 +09:00
parent 81ad315312
commit c05e1e23ee
2 changed files with 26 additions and 4 deletions

View File

@ -3828,3 +3828,17 @@ func TestIssue303(t *testing.T) {
t.Fatalf("failed to decode. count = %d type = %s value = %v", v.Count, v.Type, v.Value) t.Fatalf("failed to decode. count = %d type = %s value = %v", v.Count, v.Type, v.Value)
} }
} }
func TestIssue327(t *testing.T) {
var v struct {
Date time.Time `json:"date"`
}
dec := json.NewDecoder(strings.NewReader(`{"date": "2021-11-23T13:47:30+01:00"})`))
if err := dec.DecodeContext(context.Background(), &v); err != nil {
t.Fatal(err)
}
expected := "2021-11-23T13:47:30+01:00"
if got := v.Date.Format(time.RFC3339); got != expected {
t.Fatalf("failed to decode. expected %q but got %q", expected, got)
}
}

View File

@ -1,6 +1,7 @@
package decoder package decoder
import ( import (
"context"
"encoding/json" "encoding/json"
"unsafe" "unsafe"
@ -46,13 +47,20 @@ func (d *unmarshalJSONDecoder) DecodeStream(s *Stream, depth int64, p unsafe.Poi
typ: d.typ, typ: d.typ,
ptr: p, ptr: p,
})) }))
switch v := v.(type) {
case unmarshalerContext:
var ctx context.Context
if (s.Option.Flags & ContextOption) != 0 { if (s.Option.Flags & ContextOption) != 0 {
if err := v.(unmarshalerContext).UnmarshalJSON(s.Option.Context, dst); err != nil { ctx = s.Option.Context
} else {
ctx = context.Background()
}
if err := v.UnmarshalJSON(ctx, dst); err != nil {
d.annotateError(s.cursor, err) d.annotateError(s.cursor, err)
return err return err
} }
} else { case json.Unmarshaler:
if err := v.(json.Unmarshaler).UnmarshalJSON(dst); err != nil { if err := v.UnmarshalJSON(dst); err != nil {
d.annotateError(s.cursor, err) d.annotateError(s.cursor, err)
return err return err
} }