-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathclient.go
76 lines (66 loc) · 1.51 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
package apnsapi
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
)
func NewClient(host string, client *http.Client) *Client {
return &Client{
host: host,
client: client,
}
}
type Client struct {
host string
client *http.Client
}
func (c *Client) Do(token string, header *Header, payload []byte) (*Response, error) {
req, err := c.NewRquest(token, header, bytes.NewReader(payload))
if err != nil {
return nil, err
}
res, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer res.Body.Close()
r := &Response{
ApnsID: res.Header.Get("apns-id"),
StatusCode: res.StatusCode,
}
if res.StatusCode != http.StatusOK {
var er ErrorResponse
if err := json.NewDecoder(res.Body).Decode(&er); err != nil {
return r, err
}
return r, &er
}
return r, nil
}
func (c *Client) NewRquest(token string, header *Header, payload io.Reader) (*http.Request, error) {
url := fmt.Sprintf("%s/3/device/%s", c.host, token)
req, err := http.NewRequest("POST", url, payload)
if err != nil {
return nil, err
}
if header != nil {
if header.ApnsID != "" {
req.Header.Set("apns-id", header.ApnsID)
}
if header.ApnsExpiration != "" {
req.Header.Set("apns-expiration", header.ApnsExpiration)
}
if header.ApnsPriority != "" {
req.Header.Set("apns-priority", header.ApnsPriority)
}
if header.ApnsTopic != "" {
req.Header.Set("apns-topic", header.ApnsTopic)
}
if header.Authorization != "" {
req.Header.Set("authorization", header.Authorization)
}
}
return req, err
}