Skip to content

Commit 80b7799

Browse files
author
hechenglong
committed
fix: Fixed functions of decodeJson do not return.
1 parent c639081 commit 80b7799

File tree

2 files changed

+47
-1
lines changed

2 files changed

+47
-1
lines changed

response.go

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -233,7 +233,9 @@ func (r *Response) readAll() (err error) {
233233
}
234234

235235
if _, ok := r.Body.(*copyReadCloser); ok {
236-
_, err = ioReadAll(r.Body)
236+
var data []byte
237+
data, err = ioReadAll(r.Body)
238+
r.Body = io.NopCloser(bytes.NewReader(data))
237239
} else {
238240
r.bodyBytes, err = ioReadAll(r.Body)
239241
closeq(r.Body)

stream_test.go

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package resty
2+
3+
import (
4+
"bytes"
5+
"io"
6+
"net/http"
7+
"net/http/httptest"
8+
"testing"
9+
)
10+
11+
func TestDecodeJSONWhenResponseBodyIsNull(t *testing.T) {
12+
r := &Response{
13+
Body: io.NopCloser(bytes.NewReader([]byte("null"))),
14+
}
15+
r.wrapCopyReadCloser()
16+
err := r.readAll()
17+
assertNil(t, err)
18+
19+
var result map[int]int
20+
err = decodeJSON(r.Body, &result)
21+
assertNil(t, err)
22+
assertNil(t, result)
23+
}
24+
25+
func TestGetMethodWhenResponseIsNull(t *testing.T) {
26+
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
27+
w.Write([]byte("null"))
28+
}))
29+
30+
client := New().SetRetryCount(3).EnableGenerateCurlCmd()
31+
32+
var x any
33+
resp, err := client.R().SetBody("{}").
34+
SetHeader("Content-Type", "application/json; charset=utf-8").
35+
SetForceResponseContentType("application/json").
36+
SetAllowMethodGetPayload(true).
37+
SetResponseBodyUnlimitedReads(true).
38+
SetResult(&x).
39+
Get(server.URL + "/test")
40+
41+
assertNil(t, err)
42+
assertEqual(t, "null", resp.String())
43+
assertEqual(t, nil, x)
44+
}

0 commit comments

Comments
 (0)