forked from gjbae1212/fluent-bit-pubsub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pubsub.go
61 lines (49 loc) · 1.34 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
package main
import (
"context"
"fmt"
"cloud.google.com/go/pubsub"
"github.com/pkg/errors"
)
type Keeper interface {
Send(ctx context.Context, data []byte, attributes map[string]string) *pubsub.PublishResult
Stop()
}
type GooglePubSub struct {
client *pubsub.Client
topic *pubsub.Topic
}
func NewKeeper(projectId, topicName string,
publishSetting *pubsub.PublishSettings) (Keeper, error) {
if projectId == "" || topicName == "" {
return nil, fmt.Errorf("[err] NewKeeper empty params")
}
ctx := context.Background()
// ADC based authentication
// https://cloud.google.com/docs/authentication/application-default-credentials
client, err := pubsub.NewClient(ctx, projectId)
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, attributes map[string]string) *pubsub.PublishResult {
if len(data) == 0 {
return nil
}
msg := &pubsub.Message{Data: data}
if attributes != nil {
msg.Attributes = attributes
}
return gps.topic.Publish(ctx, msg)
}
func (gps *GooglePubSub) Stop() {
gps.topic.Stop()
}