-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
115 lines (103 loc) · 2.24 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"bufio"
"context"
"fmt"
"log"
"os"
"strings"
"cloud.google.com/go/pubsub"
"google.golang.org/api/iterator"
)
type Config struct {
Client *pubsub.Client
Topics map[string]*pubsub.Topic
Context context.Context
}
func main() {
if len(os.Args) < 1 {
log.Fatal("You must pass the emulator's projectID as argument")
} else if len(os.Args) > 2 {
log.Fatal("You can pass only the projectID as argument")
}
projectID := os.Args[1]
ctx := context.Background()
c, err := pubsub.NewClient(ctx, projectID)
if err != nil {
log.Println(err)
return
}
app := Config{
Client: c,
Context: ctx,
Topics: map[string]*pubsub.Topic{},
}
reader := bufio.NewReader(os.Stdin)
fmt.Println("Pub/Sub emulator toolkit")
fmt.Println("------------------------")
fmt.Println("[!] newtopic <topic-name>")
fmt.Println("[!] publish <topic> <data> <attributes> ('data' field can have only oneliners)")
fmt.Println("[!] showtopics")
fmt.Println("[!] showsubs")
fmt.Println("[!] exit")
for {
fmt.Print("> ")
input, _ := reader.ReadString('\n')
input = strings.TrimSuffix(input, "\n")
commands := strings.Split(input, " ")
switch commands[0] {
case "newtopic":
topicID := commands[1]
t, err := app.Client.CreateTopic(ctx, topicID)
if err != nil {
fmt.Println(err)
}
app.Topics[topicID] = t
fmt.Println(t.String())
case "showtopics":
it := app.Client.Topics(app.Context)
for {
t, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
log.Println(err)
continue
}
fmt.Println(t)
}
case "publish":
topic := app.Topics[commands[1]]
res := topic.Publish(app.Context, &pubsub.Message{
Data: []byte(commands[2]),
Attributes: map[string]string{
"event": commands[3],
},
})
msgID, err := res.Get(ctx)
if err != nil {
log.Println(err)
continue
}
log.Printf("Message published with ID: %q\n", msgID)
case "showsubs":
it := app.Client.Subscriptions(ctx)
for {
t, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
log.Println(err)
continue
}
fmt.Println(t)
}
case "exit":
os.Exit(0)
default:
fmt.Printf("%q is not a valid input\n", input)
}
}
}