fix: handle the scenarios that content-length is invalid (#2313)

This commit is contained in:
Kevin Wan
2022-08-28 15:41:02 +08:00
committed by GitHub
parent d9620bb072
commit 5d00dfb962
2 changed files with 112 additions and 4 deletions

View File

@@ -1,6 +1,8 @@
package httpc
import (
"bytes"
"io"
"net/http"
"strings"
@@ -27,13 +29,24 @@ func ParseHeaders(resp *http.Response, val interface{}) error {
func ParseJsonBody(resp *http.Response, val interface{}) error {
defer resp.Body.Close()
if withJsonBody(resp) {
return mapping.UnmarshalJsonReader(resp.Body, val)
if isContentTypeJson(resp) {
if resp.ContentLength > 0 {
return mapping.UnmarshalJsonReader(resp.Body, val)
}
var buf bytes.Buffer
if _, err := io.Copy(&buf, resp.Body); err != nil {
return err
}
if buf.Len() > 0 {
return mapping.UnmarshalJsonReader(&buf, val)
}
}
return mapping.UnmarshalJsonMap(nil, val)
}
func withJsonBody(r *http.Response) bool {
return r.ContentLength > 0 && strings.Contains(r.Header.Get(header.ContentType), header.ApplicationJson)
func isContentTypeJson(r *http.Response) bool {
return strings.Contains(r.Header.Get(header.ContentType), header.ApplicationJson)
}