支持一下~
学习了代码。然后我想到一个问题。JSON()方法为什么不直接用 json.Decoder 呢。基于这个想法试了一下。
JSON 方法用 Deocder 可以这样
```go
func (r *Response) JSON(v interface{}) error {
dec := json.NewDecoder(r.R.Body)
return dec.Decode(v)
}
```
Bench 代码
```go
func BenchmarkResponse_JSON(b *testing.B) {
type testData struct {
JSON struct {
Msg string `json:"msg"`
Num int `json:"num"`
} `json:"json"`
}
ts := httptest.NewServer( http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
dec := json.NewDecoder(r.Body)
var data testData
dec.Decode(&data.JSON)
enc := json.NewEncoder(w)
enc.Encode(data)
}))
resp :=
reqwest.Post(ts.URL).
JSON(
reqwest.Data{
"msg": "hello world",
"num": 2019,
}).
Send().
EnsureStatusOk()
b.ResetTimer()
for i:=0;i<b.N;i++ {
var retData testData
resp.JSON(&retData)
}
}
```
结果如下
## Unmarshal
```plain
$ go test -v -run="none" -bench="BenchmarkResponse_JSON" -benchtime="3s" -benchmem
goos: linux
goarch: amd64
pkg:
github.com/winterssy/reqwestBenchmarkResponse_JSON-4 5000000 959 ns/op 544 B/op 2 allocs/op
PASS
ok
github.com/winterssy/reqwest 5.895s
```
## Decoder
```plain
$ go test -v -run="none" -bench="BenchmarkResponse_JSON" -benchtime="3s" -benchmem
goos: linux
goarch: amd64
pkg:
github.com/winterssy/reqwestBenchmarkResponse_JSON-4 10000000 713 ns/op 896 B/op 3 allocs/op
PASS
ok
github.com/winterssy/reqwest 7.758s
```
跟我设想的不太一样。还以为 Decoder 会更快。为什么会这样呢?