Skip to content

Commit

Permalink
fix: panic when decoding time.Time with context
Browse files Browse the repository at this point in the history
close #327
  • Loading branch information
orisano committed Jan 25, 2022
1 parent 81ad315 commit c05e1e2
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
14 changes: 14 additions & 0 deletions decode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

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)
}
}
16 changes: 12 additions & 4 deletions internal/decoder/unmarshal_json.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package decoder

import (
"context"
"encoding/json"
"unsafe"

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

0 comments on commit c05e1e2

Please sign in to comment.