-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproducer.go
60 lines (46 loc) · 1.18 KB
/
producer.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
package grok
import (
"context"
"encoding/json"
"time"
"cloud.google.com/go/pubsub"
)
// PubSubProducer ...
type PubSubProducer struct {
client *pubsub.Client
}
// NewPubSubProducer ...
func NewPubSubProducer(client *pubsub.Client) *PubSubProducer {
return &PubSubProducer{client: client}
}
// Publish ...
func (p *PubSubProducer) Publish(topicID string, data interface{}) error {
return p.PublishWihAttribrutes(topicID, data, nil)
}
// PublishWihAttribrutes ...
func (p *PubSubProducer) PublishWihAttribrutes(topicID string, data interface{}, attributes map[string]string) error {
body, err := json.Marshal(data)
if err != nil {
return err
}
topic, err := createTopicIfNotExists(p.client, topicID)
if err != nil {
return err
}
_, err = topic.
Publish(context.Background(), &pubsub.Message{
Data: body,
PublishTime: time.Now(),
Attributes: attributes,
}).
Get(context.Background())
return err
}
func createTopicIfNotExists(client *pubsub.Client, id string) (*pubsub.Topic, error) {
topic := client.Topic(id)
exists, _ := topic.Exists(context.Background())
if exists {
return topic, nil
}
return client.CreateTopic(context.Background(), id)
}