fix: handle the scenarios that content-length is invalid (#2313)
This commit is contained in:
@@ -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)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user