Files
go-zero/rest/httpc/responses.go

38 lines
976 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-03-23 18:24:44 +08:00
// ParseHeaders parses the rsponse headers.
2022-03-23 17:58:21 +08:00
func ParseHeaders(resp *http.Response, val interface{}) error {
return encoding.ParseHeaders(resp.Header, val)
}
2022-03-23 18:24:44 +08:00
// ParseJsonBody parses the rsponse body, which should be in json content type.
2022-03-23 17:58:21 +08:00
func ParseJsonBody(resp *http.Response, val interface{}) error {
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
}