-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
84 lines (76 loc) · 1.93 KB
/
client.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
package jpushclient
import (
"encoding/base64"
"encoding/json"
"fmt"
"io"
"net/http"
"runtime"
)
type Client struct {
AppKey string
MasterSecret string
pushUrl string
imageUrl string
adminUrl string
reportUrl string
deviceUrl string
}
type Response struct {
data []byte
}
func NewClient(appKey, masterSecret string) *Client {
client := &Client{AppKey: appKey, MasterSecret: masterSecret}
client.pushUrl = "https://api.jpush.cn"
client.reportUrl = "https://report.jpush.cn"
client.deviceUrl = "https://device.jpush.cn"
client.imageUrl = "https://api.jpush.cn/v3/images"
client.adminUrl = "https://admin.jpush.cn"
return client
}
func (c *Client) getAuthorization(isGroup bool) string {
str := c.AppKey + ":" + c.MasterSecret
if isGroup {
str = "group-" + str
}
buf := []byte(str)
return fmt.Sprintf("Basic %s", base64.StdEncoding.EncodeToString(buf))
}
func (c *Client) getUserAgent() string {
return fmt.Sprintf("(%s) go/%s", runtime.GOOS, runtime.Version())
}
func (c *Client) request(method, link string, body io.Reader, isGroup bool) (*Response, error) {
req, err := http.NewRequest(method, link, body)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", c.getAuthorization(isGroup))
req.Header.Set("User-Agent", c.getUserAgent())
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(resp.Body)
buf, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
return &Response{data: buf}, nil
}
func (res *Response) Array() ([]any, error) {
list := make([]any, 0)
err := json.Unmarshal(res.data, &list)
return list, err
}
func (res *Response) Map() (map[string]any, error) {
result := make(map[string]any)
err := json.Unmarshal(res.data, &result)
return result, err
}
func (res *Response) Bytes() []byte {
return res.data
}