-
Notifications
You must be signed in to change notification settings - Fork 0
/
subscribe.go
78 lines (71 loc) · 1.87 KB
/
subscribe.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
71
72
73
74
75
76
77
78
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"log"
"strconv"
"cloud.google.com/go/pubsub"
"github.com/google/uuid"
"github.com/spf13/cobra"
)
func newSubscribeCommand(ctx context.Context) *cobra.Command {
command := cobra.Command{
Use: "subscribe",
Short: "Subscribe to topics in the emulator",
Args: cobra.NoArgs,
Run: func(command *cobra.Command, args []string) {
host := command.Flag("host").Value.String()
projectID := command.Flag("project_id").Value.String()
client, err := setupClient(ctx, host, projectID)
if err != nil {
log.Fatalln(err)
}
topicID := command.Flag("topic_id").Value.String()
for {
message, err := subscriptionTopic(ctx, client, topicID)
if err != nil {
log.Fatalln(err)
}
var out bytes.Buffer
json.Indent(&out, []byte(*message), "", " ")
fmt.Println(out.String())
}
},
}
command.Flags().StringP("topic_id", "t", "", "topic id (required)")
if err := command.MarkFlagRequired("topic_id"); err != nil {
log.Fatalln(err)
}
return &command
}
// Subscribe to topics in the emulator
func subscriptionTopic(ctx context.Context, client *pubsub.Client, topicID string) (*string, error) {
topic, err := getTopic(ctx, client, topicID)
if err != nil {
return nil, err
}
subscription, err := client.CreateSubscription(ctx, "sub-"+topicID+"-"+uuid.New().String(), pubsub.SubscriptionConfig{Topic: topic})
if err != nil {
return nil, err
}
cctx, cancel := context.WithCancel(ctx)
type result struct {
message string
err error
}
ch := make(chan result)
go func() {
err = subscription.Receive(cctx, func(_ context.Context, message *pubsub.Message) {
defer cancel()
message.Ack()
unquoted, err := strconv.Unquote(string(message.Data))
ch <- result{message: unquoted, err: err}
})
}()
select {
case result := <-ch:
return &result.message, result.err
}
}