Skip to content

Commit 9c15332

Browse files
fix(client): don't panic on marshal with extra null field
1 parent 814dd8b commit 9c15332

File tree

2 files changed

+31
-1
lines changed

2 files changed

+31
-1
lines changed

internal/apijson/decoder.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -461,7 +461,7 @@ func (d *decoderBuilder) newStructTypeDecoder(t reflect.Type) decoderFunc {
461461
}
462462

463463
// Handle null [param.Opt]
464-
if itemNode.Type == gjson.Null && dest.Type().Implements(reflect.TypeOf((*param.Optional)(nil)).Elem()) {
464+
if itemNode.Type == gjson.Null && dest.IsValid() && dest.Type().Implements(reflect.TypeOf((*param.Optional)(nil)).Elem()) {
465465
dest.Addr().Interface().(json.Unmarshaler).UnmarshalJSON([]byte(itemNode.Raw))
466466
continue
467467
}

internal/apijson/decoderesp_test.go

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
package apijson_test
2+
3+
import (
4+
"encoding/json"
5+
"github.com/openai/openai-go/internal/apijson"
6+
"github.com/openai/openai-go/packages/respjson"
7+
"testing"
8+
)
9+
10+
type StructWithNullExtraField struct {
11+
Results []string `json:"results,required"`
12+
JSON struct {
13+
Results respjson.Field
14+
ExtraFields map[string]respjson.Field
15+
raw string
16+
} `json:"-"`
17+
}
18+
19+
func (r *StructWithNullExtraField) UnmarshalJSON(data []byte) error {
20+
return apijson.UnmarshalRoot(data, r)
21+
}
22+
23+
func TestDecodeWithNullExtraField(t *testing.T) {
24+
raw := `{"something_else":null}`
25+
var dst *StructWithNullExtraField
26+
err := json.Unmarshal([]byte(raw), &dst)
27+
if err != nil {
28+
t.Fatalf("error: %s", err.Error())
29+
}
30+
}

0 commit comments

Comments
 (0)