forked from mercari/gaurun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
apns_http2.go
109 lines (90 loc) · 2.45 KB
/
apns_http2.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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package gaurun
import (
"crypto/tls"
"encoding/json"
"net"
"net/http"
"time"
"github.com/RobotsAndPencils/buford/payload"
"github.com/RobotsAndPencils/buford/payload/badge"
"github.com/RobotsAndPencils/buford/push"
"golang.org/x/net/http2"
)
func NewTransportHttp2(cert tls.Certificate) (*http.Transport, error) {
config := &tls.Config{
Certificates: []tls.Certificate{cert},
}
config.BuildNameToCertificate()
transport := &http.Transport{
TLSClientConfig: config,
MaxIdleConnsPerHost: ConfGaurun.Ios.KeepAliveConns,
Dial: (&net.Dialer{
Timeout: time.Duration(ConfGaurun.Ios.Timeout) * time.Second,
KeepAlive: time.Duration(keepAliveInterval(ConfGaurun.Ios.KeepAliveTimeout)) * time.Second,
}).Dial,
IdleConnTimeout: time.Duration(ConfGaurun.Ios.KeepAliveTimeout) * time.Second,
}
if err := http2.ConfigureTransport(transport); err != nil {
return nil, err
}
return transport, nil
}
func NewApnsClientHttp2(certPath, keyPath string) (*http.Client, error) {
cert, err := tls.LoadX509KeyPair(certPath, keyPath)
if err != nil {
return nil, err
}
transport, err := NewTransportHttp2(cert)
if err != nil {
return nil, err
}
return &http.Client{
Transport: transport,
Timeout: time.Duration(ConfGaurun.Ios.Timeout) * time.Second,
}, nil
}
func NewApnsServiceHttp2(client *http.Client) *push.Service {
var host string
if ConfGaurun.Ios.Sandbox {
host = push.Development
} else {
host = push.Production
}
return &push.Service{
Client: client,
Host: host,
}
}
func NewApnsPayloadHttp2(req *RequestGaurunNotification) map[string]interface{} {
p := payload.APS{
Alert: payload.Alert{Body: req.Message},
Badge: badge.New(uint(req.Badge)),
Sound: req.Sound,
ContentAvailable: req.ContentAvailable,
MutableContent: req.MutableContent,
}
pm := p.Map()
if len(req.Extend) > 0 {
for _, extend := range req.Extend {
pm[extend.Key] = extend.Value
}
}
return pm
}
func NewApnsHeadersHttp2(req *RequestGaurunNotification) *push.Headers {
headers := &push.Headers{
Topic: ConfGaurun.Ios.Topic,
}
if req.Expiry > 0 {
headers.Expiration = time.Now().Add(time.Duration(int64(req.Expiry)) * time.Second).UTC()
}
return headers
}
func ApnsPushHttp2(token string, service *push.Service, headers *push.Headers, payload map[string]interface{}) error {
b, err := json.Marshal(payload)
if err != nil {
return err
}
_, err = service.Push(token, headers, b)
return err
}