-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtopic.go
55 lines (45 loc) · 964 Bytes
/
topic.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"
"github.com/mpsdantas/bottle/pkg/log"
)
type Topic interface {
Publish(ctx context.Context, event string, value interface{})
}
type topic struct {
tp *pubsub.Topic
}
func (t *topic) Publish(ctx context.Context, event string, value interface{}) {
go func(c context.Context) {
data, err := json.Marshal(value)
if err != nil {
log.Error(c, "could not marshal data",
log.Err(err),
)
return
}
for i := 0; i < 100; i++ {
result := t.tp.Publish(c, &pubsub.Message{
Data: data,
Attributes: map[string]string{
"x-event": event,
},
})
id, err := result.Get(c)
if err != nil {
log.Error(c, "could not publish message data",
log.Err(err),
)
time.Sleep(1 * time.Second)
continue
}
log.Info(c, "message published successfully",
log.String("id", id),
)
break
}
}(WithoutCancel(ctx))
}