-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
http_util.go
45 lines (35 loc) · 879 Bytes
/
http_util.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
package util
import (
"encoding/json"
"fmt"
"io"
"net/http"
)
// GetHTTPResponse 处理HTTP结果,返回序列化的json
func GetHTTPResponse(resp *http.Response, err error, result interface{}) error {
body, err := GetHTTPResponseOrg(resp, err)
if err == nil {
// log.Println(string(body))
if len(body) != 0 {
err = json.Unmarshal(body, &result)
}
}
return err
}
// GetHTTPResponseOrg 处理HTTP结果,返回byte
func GetHTTPResponseOrg(resp *http.Response, err error) ([]byte, error) {
if err != nil {
return nil, err
}
defer resp.Body.Close()
lr := io.LimitReader(resp.Body, 1024000)
body, err := io.ReadAll(lr)
if err != nil {
return nil, err
}
// 300及以上状态码都算异常
if resp.StatusCode >= 300 {
err = fmt.Errorf(LogStr("返回内容: %s ,返回状态码: %d", string(body), resp.StatusCode))
}
return body, err
}