forked from legalforce-oss/fluent-bit-pubsub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pubsub.go
66 lines (54 loc) · 1.56 KB
/
pubsub.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
package main
import (
"context"
"fmt"
"io/ioutil"
"cloud.google.com/go/pubsub"
"github.com/pkg/errors"
"golang.org/x/oauth2/google"
"google.golang.org/api/option"
)
type Keeper interface {
Send(ctx context.Context, data []byte, attr map[string]string) *pubsub.PublishResult
Stop()
}
type GooglePubSub struct {
client *pubsub.Client
topic *pubsub.Topic
}
func NewKeeper(projectId, topicName, jwtPath string,
publishSetting *pubsub.PublishSettings) (Keeper, error) {
if projectId == "" || topicName == "" || jwtPath == "" {
return nil, fmt.Errorf("[err] NewKeeper empty params")
}
keyBytes, err := ioutil.ReadFile(jwtPath)
if err != nil {
return nil, errors.Wrap(err, "[err] jwt path")
}
config, err := google.JWTConfigFromJSON(keyBytes, pubsub.ScopePubSub)
if err != nil {
return nil, errors.Wrap(err, "[err] jwt config")
}
ctx := context.Background()
client, err := pubsub.NewClient(ctx, projectId, option.WithTokenSource(config.TokenSource(ctx)))
if err != nil {
return nil, errors.Wrap(err, "[err] pubsub client")
}
topic := client.Topic(topicName)
if publishSetting != nil {
topic.PublishSettings = *publishSetting
} else {
topic.PublishSettings = pubsub.DefaultPublishSettings
}
pubs := &GooglePubSub{client: client, topic: topic}
return Keeper(pubs), nil
}
func (gps *GooglePubSub) Send(ctx context.Context, data []byte, attr map[string]string) *pubsub.PublishResult {
if len(data) == 0 {
return nil
}
return gps.topic.Publish(ctx, &pubsub.Message{Data: data, Attributes: attr})
}
func (gps *GooglePubSub) Stop() {
gps.topic.Stop()
}