forked from crow-misia/go-push-receiver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
105 lines (93 loc) · 2.4 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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
* Copyright (c) 2019 Zenichi Amano
*
* This file is part of go-push-receiver, which is MIT licensed.
* See http://opensource.org/licenses/MIT
*/
// Package pushreceiver is Push Message Receiver library from FCM.
package pushreceiver
import (
"context"
"crypto/tls"
"github.com/pkg/errors"
"io"
"net"
"net/http"
"time"
)
// httpClient defines the minimal interface needed for an http.Client to be implemented.
type httpClient interface {
Do(*http.Request) (*http.Response, error)
}
// Client is FCM Push receive client.
type Client struct {
senderID string
log ilogger
httpClient httpClient
tlsConfig *tls.Config
creds *FCMCredentials
dialer *net.Dialer
backoff *Backoff
heartbeat *Heartbeat
receivedPersistentID []string
Events chan Event
gcmCheckin bool
}
// New returns a new FCM push receive client instance.
func New(senderID string, options ...ClientOption) *Client {
c := &Client{
senderID: senderID,
Events: make(chan Event, 50),
}
for _, option := range options {
option(c)
}
// set defaults
if c.backoff == nil {
c.backoff = NewBackoff(defaultBackoffBase*time.Second, defaultBackoffMax*time.Second)
}
if c.heartbeat == nil {
c.heartbeat = newHeartbeat(defaultHeartbeatPeriod * time.Minute)
}
if c.tlsConfig == nil {
c.tlsConfig = &tls.Config{
InsecureSkipVerify: false,
MinVersion: tls.VersionTLS13,
}
}
if c.dialer == nil {
c.dialer = &net.Dialer{
Timeout: defaultDialTimeout * time.Second,
KeepAlive: defaultKeepAlive * time.Minute,
FallbackDelay: 30 * time.Millisecond,
}
}
if c.httpClient == nil {
c.httpClient = &http.Client{
Transport: &http.Transport{
TLSClientConfig: c.tlsConfig,
},
}
}
if c.log == nil {
c.log = &discard{}
}
c.log.Print("Sender ID: ", c.senderID)
return c
}
func (c *Client) post(ctx context.Context, url string, body io.Reader, headerSetter func(*http.Header)) (*http.Response, error) {
if ctx == nil {
ctx = context.Background()
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, body)
if err != nil {
return nil, errors.Wrap(err, "create post request error")
}
headerSetter(&req.Header)
return c.httpClient.Do(req)
}
func closeResponse(res *http.Response) error {
defer res.Body.Close()
_, err := io.Copy(io.Discard, res.Body)
return err
}