-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.go
69 lines (61 loc) · 1.56 KB
/
request.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
package gomeng
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"strings"
"time"
)
type Payload map[string]interface{}
func (c *Client) genRequestParams(payload Payload, reqType requestType, deviceTokens ...string) map[string]interface{} {
p := map[string]interface{}{
"appkey": c.cfg.AppKey,
"timestamp": time.Now().Unix(),
"type": reqType,
"payload": payload,
"production_mode": c.cfg.ProductionMode,
}
if len(deviceTokens) > 0 {
p["device_tokens"] = strings.Join(deviceTokens, ",")
}
return p
}
func (c *Client) doPost(ctx context.Context, param map[string]interface{}, endpoint string) (*ResponseMessage, error) {
// e.g. https://msgapi.umeng.com/api/send
url, err := url.JoinPath(baseURL, endpoint)
if err != nil {
return nil, err
}
b, err := json.Marshal(param)
if err != nil {
return nil, err
}
// do sign
sign, err := sign(http.MethodPost, url, c.cfg.AppSecret, b)
if err != nil {
return nil, fmt.Errorf("sign error: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, joinSign(url, sign), bytes.NewReader(b))
if err != nil {
return nil, fmt.Errorf("new request error: %w", err)
}
req.Header.Set("Content-Type", "application/json")
resp, err := c.rawhttp.Do(req)
if err != nil {
return nil, fmt.Errorf("request error: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, err
}
rm := &ResponseMessage{}
if err := json.Unmarshal(body, rm); err != nil {
return nil, err
}
return rm, nil
}