Skip to content

Commit dfd870a

Browse files
fix: handle empty bodies in WithJSONSet
1 parent 907273a commit dfd870a

File tree

1 file changed

+13
-4
lines changed

1 file changed

+13
-4
lines changed

option/requestoption.go

+13-4
Original file line numberDiff line numberDiff line change
@@ -169,17 +169,26 @@ func WithQueryDel(key string) RequestOption {
169169
// [sjson format]: https://github.com/tidwall/sjson
170170
func WithJSONSet(key string, value interface{}) RequestOption {
171171
return requestconfig.RequestOptionFunc(func(r *requestconfig.RequestConfig) (err error) {
172-
if buffer, ok := r.Body.(*bytes.Buffer); ok {
173-
b := buffer.Bytes()
172+
var b []byte
173+
174+
if r.Body == nil {
175+
b, err = sjson.SetBytes(nil, key, value)
176+
if err != nil {
177+
return err
178+
}
179+
} else if buffer, ok := r.Body.(*bytes.Buffer); ok {
180+
b = buffer.Bytes()
174181
b, err = sjson.SetBytes(b, key, value)
175182
if err != nil {
176183
return err
177184
}
178-
r.Body = bytes.NewBuffer(b)
179185
return nil
186+
} else {
187+
return fmt.Errorf("cannot use WithJSONSet on a body that is not serialized as *bytes.Buffer")
180188
}
181189

182-
return fmt.Errorf("cannot use WithJSONSet on a body that is not serialized as *bytes.Buffer")
190+
r.Body = bytes.NewBuffer(b)
191+
return nil
183192
})
184193
}
185194

0 commit comments

Comments
 (0)