-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.go
87 lines (78 loc) · 1.99 KB
/
http.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
package util
import (
"bytes"
"encoding/json"
"errors"
"io"
"log"
"net/http"
)
// HttpRequestJson 发送http请求。请求体和响应体都是json。
func HttpRequestJson(method string, url string, headers map[string]string, req interface{}, resp interface{}) error {
reqBody, _ := json.Marshal(req)
request, err := http.NewRequest(method, url, bytes.NewBuffer(reqBody))
if err != nil {
log.Printf("http.NewReuqest error: %v", err)
return err
}
// default content-type
if _, ok := headers["Content-Type"]; !ok {
request.Header.Add("Content-Type", "application/json")
}
// headers
for headerKey, headerValue := range headers {
request.Header.Add(headerKey, headerValue)
}
httpResp, err := http.DefaultClient.Do(request)
if err != nil {
log.Printf("req error: %v", err)
return err
}
defer httpResp.Body.Close()
respBody, err := io.ReadAll(httpResp.Body)
if err != nil {
return err
}
log.Printf("respBody: %v", string(respBody))
err = json.Unmarshal(respBody, &resp)
if err != nil {
log.Printf("resp unmarshal error: %v", err)
return err
}
return nil
}
// HttpRequest 发送request
// func SendRequest(url string, body io.Reader, addHeaders map[string]string, method string) ([]byte, error) {
func HttpRequest(method, url string, headers map[string]string, body io.Reader) ([]byte, error) {
// 1、创建req
req, err := http.NewRequest(method, url, body)
if err != nil {
log.Println(err)
return nil, err
}
// req.Header.Add("Content-Type", "application/json")
// 2、设置headers
for k, v := range headers {
req.Header.Add(k, v)
}
// 3、发送http请求
response, err := http.DefaultClient.Do(req)
if err != nil {
log.Println(err)
return nil, err
}
defer response.Body.Close()
if response.StatusCode != 200 {
err = errors.New("http status err")
log.Println(err)
return nil, err
}
// 4、结果读取
resp, err := io.ReadAll(response.Body)
if err != nil {
log.Println(err)
return nil, err
}
// log.Println(string(resp))
return resp, nil
}