-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpubsubkit_subscription.go
47 lines (37 loc) · 1.03 KB
/
pubsubkit_subscription.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
package pubsubkit
import (
"context"
"cloud.google.com/go/pubsub"
"github.com/pkg/errors"
)
// NewPubSubSubscription returns new PubSub topic subscriber in 5s timeout.
func NewPubSubSubscription(
client *pubsub.Client,
subID string,
cfg pubsub.SubscriptionConfig,
opts ...Option,
) (*pubsub.Subscription, error) {
opt := newDefaultOptions()
for _, o := range opts {
o(opt)
}
sub := client.Subscription(subID)
connectCtx, cancel := context.WithTimeout(context.Background(), connectTimeout)
defer cancel()
if opt.checkExists {
ok, err := sub.Exists(connectCtx)
if err != nil {
return nil, errors.Wrapf(err, "pubsubkit: failed to check subscription %s existence", subID)
}
if !ok {
if !opt.autoCreate {
return nil, errors.Wrapf(ErrSubscriptionNotFound, "pubsubkit: failed create subscription %s", subID)
}
sub, err = client.CreateSubscription(connectCtx, subID, cfg)
if err != nil {
return nil, errors.Wrapf(err, "pubsubkit: failed create pubsub subscription %s", subID)
}
}
}
return sub, nil
}