-
Notifications
You must be signed in to change notification settings - Fork 0
/
publish_log.go
45 lines (36 loc) · 914 Bytes
/
publish_log.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
package publish_log
import (
"context"
"encoding/json"
"fmt"
"cloud.google.com/go/pubsub"
"google.golang.org/api/option"
)
type dataConfig struct {
ProjectID string
TopicID string
CredentialFileJson []byte
}
func PublishLog(ctx context.Context, data map[string]interface{}, config []byte) error {
var cfg dataConfig
json.Unmarshal(config, &cfg)
d, err := json.Marshal(data)
if err != nil {
fmt.Printf("error marshal :", err)
}
client, err := pubsub.NewClient(ctx, cfg.ProjectID, option.WithCredentialsJSON(cfg.CredentialFileJson))
if err != nil {
return fmt.Errorf("pubsub: NewClient: %v", err)
}
defer client.Close()
t := client.Topic(cfg.TopicID)
result := t.Publish(ctx, &pubsub.Message{
Data: []byte(d),
})
id, err := result.Get(ctx)
if err != nil {
return fmt.Errorf("pubsub: result.Get: %v", err)
}
fmt.Printf("Published a message; msg ID: %v\n", id)
return nil
}