-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjpush.go
More file actions
109 lines (100 loc) · 2.17 KB
/
Copy pathjpush.go
File metadata and controls
109 lines (100 loc) · 2.17 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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package jpush
import (
"log"
"net/http/httputil"
"bytes"
"encoding/base64"
"encoding/json"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
)
//地址变量
const (
PushURL = "/v3/push"
)
//JPush JPush
type JPush struct {
AppKey string
MasterSecret string
Authorization string
ServerAddr string
DevMode bool
}
//NewJPush NewJPush
func NewJPush(ServerAddr, AppKey, MasterSecret, mode string) (jpush *JPush) {
if ServerAddr == "" {
ServerAddr = "https://api.jpush.cn"
}
devmode := false
if mode == "dev" {
devmode = true
}
return &JPush{
ServerAddr: ServerAddr,
AppKey: AppKey,
MasterSecret: MasterSecret,
Authorization: "Basic " + base64.StdEncoding.EncodeToString([]byte(AppKey+":"+MasterSecret)),
DevMode: devmode,
}
}
func (j *JPush) requset(req *http.Request) ([]byte, error) {
client := &http.Client{Timeout: 60 * time.Second}
req.Header.Set("Authorization", j.Authorization)
b, _ := httputil.DumpRequest(req, true)
log.Println(string(b))
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}
//createRequset 生成请求requset参数
func createRequset(surl, method string, p map[string]string, d interface{}) (req *http.Request, err error) {
buf, err := json.Marshal(d)
if d != nil && err != nil {
return nil, err
}
val := make(url.Values)
for k, v := range p {
val.Add(k, v)
}
ContentType := ""
switch method {
case "GET":
if strings.Index(surl, "?") != -1 {
surl += "&" + val.Encode()
} else {
surl += "?" + val.Encode()
}
case "POST":
if d == nil {
buf = []byte(val.Encode())
ContentType = "application/x-www-form-urlencoded"
} else {
ContentType = "application/json"
if strings.Index(surl, "?") != -1 {
surl += "&" + val.Encode()
} else {
surl += "?" + val.Encode()
}
}
default:
if strings.Index(surl, "?") != -1 {
surl += "&" + val.Encode()
} else {
surl += "?" + val.Encode()
}
}
req, err = http.NewRequest(method, surl, bytes.NewReader(buf))
if err != nil {
return nil, err
}
if ContentType != "" {
req.Header.Add("Content-Type", ContentType)
}
return req, err
}