-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
70 lines (56 loc) · 1.74 KB
/
main.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package pubsub
import (
"cloud.google.com/go/pubsub"
"context"
"fmt"
"github.com/rfizzle/log-collector/collector"
log "github.com/sirupsen/logrus"
"github.com/tidwall/pretty"
"google.golang.org/api/option"
"time"
)
type Client struct {
collector.Client
Options map[string]interface{}
}
// New will initialize and return an authorized Client
func New(options map[string]interface{}) (collector.Client, error) {
return &Client{
Options: options,
}, nil
}
func (pubsubClient *Client) Poll(timestamp time.Time, resultsChannel chan<- string, pollOffset int) (count int, currentTimestamp time.Time, err error) {
return 0, time.Now(), fmt.Errorf("unsupported client collection method")
}
func (pubsubClient *Client) Stream(streamChannel chan<- string) (cancelFunc func(), err error) {
// Get context background
ctx := context.Background()
// Setup new client
client, err := pubsub.NewClient(ctx, pubsubClient.Options["projectID"].(string), option.WithCredentialsFile(pubsubClient.Options["credentials"].(string)))
if err != nil {
return nil, err
}
// Setup received value
received := 0
// Setup subscription
sub := client.Subscription(pubsubClient.Options["subscriptionID"].(string))
// Setup context with cancel so we can add to log files routinely
cctx, cancel := context.WithCancel(ctx)
go func() {
err2 := sub.Receive(cctx, func(ctx context.Context, msg *pubsub.Message) {
streamChannel <- string(pretty.Ugly(msg.Data))
msg.Ack()
received++
})
if err2 != nil {
log.Errorf("error receiving subscription messages: %v", err)
}
}()
return cancel, nil
}
func (pubsubClient *Client) ClientType() collector.ClientType {
return collector.ClientTypeStream
}
func (pubsubClient *Client) Exit() (err error) {
return nil
}