go-zero/rest/httpc/responses.go

40 lines
1004 B
Go
Raw Normal View History

2022-03-23 17:58:21 +08:00
package httpc
import (
"net/http"
"strings"
"github.com/zeromicro/go-zero/core/mapping"
"github.com/zeromicro/go-zero/rest/internal/encoding"
"github.com/zeromicro/go-zero/rest/internal/header"
2022-03-23 17:58:21 +08:00
)
2022-03-23 18:24:44 +08:00
// Parse parses the response.
2022-03-23 17:58:21 +08:00
func Parse(resp *http.Response, val interface{}) error {
if err := ParseHeaders(resp, val); err != nil {
return err
}
return ParseJsonBody(resp, val)
}
2022-07-27 09:11:15 +08:00
// ParseHeaders parses the response headers.
2022-03-23 17:58:21 +08:00
func ParseHeaders(resp *http.Response, val interface{}) error {
return encoding.ParseHeaders(resp.Header, val)
}
2022-07-27 09:11:15 +08:00
// ParseJsonBody parses the response body, which should be in json content type.
2022-03-23 17:58:21 +08:00
func ParseJsonBody(resp *http.Response, val interface{}) error {
defer resp.Body.Close()
2022-03-23 17:58:21 +08:00
if withJsonBody(resp) {
return mapping.UnmarshalJsonReader(resp.Body, 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)
2022-03-23 17:58:21 +08:00
}