This repository has been archived by the owner on Aug 1, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 43
/
Copy pathpushmessage.go
executable file
·82 lines (68 loc) · 1.54 KB
/
pushmessage.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
package pushmessage
import (
"context"
firebase "firebase.google.com/go"
"firebase.google.com/go/messaging"
"google.golang.org/api/option"
)
// Firebase backend for pushmessage
type Firebase struct {
msgclient *messaging.Client
}
// Config of firebase
type Config struct {
ProjectID string
ServiceAccountID string
Bucket string
ServiceAccountFile string
DryRun bool
}
// SendOptions for firebase client
type SendOptions struct {
DryRun bool
}
// New firebase push message package
func New(ctx context.Context, config *Config) (*Firebase, error) {
var opts option.ClientOption
cfg := new(firebase.Config)
if config != nil {
cfg.ProjectID = config.ProjectID
cfg.ServiceAccountID = config.ServiceAccountID
if config.ServiceAccountFile != "" {
opts = option.WithCredentialsFile(config.ServiceAccountFile)
}
}
app, err := firebase.NewApp(ctx, cfg, opts)
if err != nil {
return nil, err
}
msgclient, err := app.Messaging(ctx)
if err != nil {
return nil, err
}
f := Firebase{
msgclient: msgclient,
}
return &f, nil
}
// Send notification
func (f *Firebase) Send(ctx context.Context, message *messaging.Message, options *SendOptions) (string, error) {
var opts SendOptions
if options != nil {
opts = *options
}
var (
id string
err error
)
if !opts.DryRun {
id, err = f.msgclient.Send(ctx, message)
} else {
// use default token if token not exists
if message.Token == "" {
message.Token = dummyToken
}
id, err = f.msgclient.SendDryRun(ctx, message)
}
return id, err
}