forked from MobClub/mobpush-websdkv3-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.go
95 lines (78 loc) · 2.02 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
88
89
90
91
92
93
94
95
package mob_push_sdk
import (
"bytes"
"crypto/md5"
"crypto/tls"
"encoding/hex"
"encoding/json"
"io/ioutil"
"net/http"
"time"
)
var gHTTPClient = CreateHTTPClient()
func GetHTTPClient() *HTTPClient {
return gHTTPClient
}
type HTTPClient struct {
client *http.Client
Sign string
Appkey string
AppSecret string
}
func CreateHTTPClient() *HTTPClient {
return &HTTPClient{client: &http.Client{
Timeout: time.Second * 30,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
}}
}
func (client *HTTPClient) Request(request *http.Request) ([]byte, error) {
response, err := client.client.Do(request)
if err != nil {
return nil, err
}
defer func() {
if response != nil && response.Body != nil {
_ = response.Body.Close()
}
}()
return ioutil.ReadAll(response.Body)
}
func (client *HTTPClient) Get(uri string) ([]byte, error) {
if request, err := http.NewRequest(http.MethodGet, uri, nil); err == nil {
return client.Request(request)
} else {
return nil, err
}
}
func (client *HTTPClient) PostJSON(pushClient *PushClient, uri string, values interface{}) ([]byte, error) {
var body []byte
if requestData, err := json.Marshal(values); err != nil {
return nil, err
} else {
body = requestData
}
client.SetSign(pushClient, body)
//fmt.Println(uri,string(body))
if request, err := http.NewRequest(http.MethodPost, uri, bytes.NewReader(body)); err == nil {
request.Header.Add("Content-Type", "application/json")
request.Header.Add("key", client.Appkey)
request.Header.Add("sign", client.Sign)
return client.Request(request)
} else {
return nil, err
}
}
func (client *HTTPClient) SetSign(pushClient *PushClient, requestJson []byte) *HTTPClient {
client.Appkey = pushClient.AppKey
client.AppSecret = pushClient.AppSecert
originString := string(requestJson) + client.AppSecret
client.Sign = getMD5Encode(originString)
return client
}
func getMD5Encode(data string) string {
h := md5.New()
h.Write([]byte(data))
return hex.EncodeToString(h.Sum(nil))
}