forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponses.go
52 lines (41 loc) · 1.16 KB
/
responses.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
package httpc
import (
"bytes"
"io"
"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"
)
// Parse parses the response.
func Parse(resp *http.Response, val any) error {
if err := ParseHeaders(resp, val); err != nil {
return err
}
return ParseJsonBody(resp, val)
}
// ParseHeaders parses the response headers.
func ParseHeaders(resp *http.Response, val any) error {
return encoding.ParseHeaders(resp.Header, val)
}
// ParseJsonBody parses the response body, which should be in json content type.
func ParseJsonBody(resp *http.Response, val any) error {
defer resp.Body.Close()
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 isContentTypeJson(r *http.Response) bool {
return strings.Contains(r.Header.Get(header.ContentType), header.ApplicationJson)
}