http_client.go
1.6 KB
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
package k3cloud
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/google/uuid"
)
//全局使用的http请求
type HttpClient struct {
HostUrl string
Cookie []*http.Cookie
}
//WrapPostData 包装发送的数据
func (hClient *HttpClient) WrapPostData(param interface{}) (*postData, error) {
data := postData{
Format: 1,
Useragent: "ApiClient",
Rid: uuid.NewString(),
Timestamp: time.Now().Format("2006-01-02"),
V: "1.0",
Parameters: param,
}
return &data, nil
}
func (hClient *HttpClient) PostRequest(api string, param interface{}) (*http.Response, error) {
data, err := hClient.WrapPostData(param)
if err != nil {
return nil, err
}
url := fmt.Sprintf("%s%s", hClient.HostUrl, api)
var buf bytes.Buffer
encoder := json.NewEncoder(&buf)
err = encoder.Encode(data)
if err != nil {
return nil, err
}
req, err := http.NewRequest(http.MethodPost, url, &buf)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
for i := range hClient.Cookie {
req.AddCookie(hClient.Cookie[i])
}
client := http.Client{
Timeout: 60 * time.Second,
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
return resp, err
}
func (hClient *HttpClient) DecodeJSON(r io.Reader, v interface{}) error {
defer io.Copy(io.Discard, r)
return json.NewDecoder(r).Decode(v)
}
func (hClient *HttpClient) InvokeApi(api string, param interface{}, respData interface{}) error {
resp, err := hClient.PostRequest(api, param)
if err != nil {
return err
}
err = hClient.DecodeJSON(resp.Body, respData)
return err
}