-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
55 lines (44 loc) · 1.03 KB
/
utils.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
package pubsub
import (
"context"
"encoding/json"
"time"
"cloud.google.com/go/pubsub"
)
func SubscribeToTopic(
ctx context.Context,
client *pubsub.Client,
topic string,
subscription string,
deadline time.Duration,
sync bool,
maxOutstandingMessages int,
fx func(ctx context.Context, msg *pubsub.Message),
) error {
t, err := CreateTopicIfNotExists(ctx, client, topic)
if err != nil {
return err
}
config := &pubsub.SubscriptionConfig{
AckDeadline: deadline,
}
s, err := CreateSubscriptionIfNotExists(ctx, client, subscription, t, config)
if err != nil {
return err
}
s.ReceiveSettings.Synchronous = sync
s.ReceiveSettings.MaxOutstandingMessages = maxOutstandingMessages
go func() {
_ = s.Receive(ctx, fx)
}()
return nil
}
func Publish(ctx context.Context, client *pubsub.Client, topic string, message interface{}) (string, error) {
data, err := json.Marshal(message)
if err != nil {
return "", err
}
t := client.Topic(topic)
result := t.Publish(ctx, &pubsub.Message{Data: data})
return result.Get(ctx)
}