-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
44 lines (37 loc) · 994 Bytes
/
client.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
package queue
import (
"context"
"encoding/json"
"cloud.google.com/go/pubsub"
"github.com/m-mizutani/goerr"
"github.com/m-mizutani/overseer/pkg/domain/model"
"google.golang.org/api/option"
)
type pubsubClient struct {
client *pubsub.Client
topic *pubsub.Topic
}
func New(ctx context.Context, projectID, topicID string, options ...option.ClientOption) (*pubsubClient, error) {
client, err := pubsub.NewClient(ctx, projectID, options...)
if err != nil {
return nil, goerr.Wrap(err, "Fail to create PubSub client")
}
topic := client.Topic(topicID)
return &pubsubClient{
client: client,
topic: topic,
}, nil
}
func (x *pubsubClient) Emit(ctx context.Context, alert *model.Alert) error {
data, err := json.Marshal(alert)
if err != nil {
return goerr.Wrap(err, "Fail to marshal alert")
}
result := x.topic.Publish(ctx, &pubsub.Message{
Data: data,
})
if _, err := result.Get(ctx); err != nil {
return goerr.Wrap(err, "Fail to publish alert")
}
return nil
}