-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathps-cli.go
85 lines (71 loc) · 1.9 KB
/
ps-cli.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
package main
import (
"context"
"encoding/json"
"flag"
"fmt"
"os"
"cloud.google.com/go/pubsub"
)
type Config struct {
ProjectID string
Topic string
}
func handleError(err error, desc string) {
if err != nil {
fmt.Println("Error during: ", desc)
fmt.Println("Error description:" , err)
os.Exit(1)
}
}
func readFile(path *string) *[]byte {
data, err := os.ReadFile(*path)
handleError(err, "os.ReadFile")
return &data
}
func unmarshal(data []byte) *Config{
var cfg Config
err := json.Unmarshal(data, &cfg)
handleError(err, "json.Unmarshal")
return &cfg
}
func readConfig(path *string) Config {
data := readFile(path)
cfg := unmarshal(*data)
return *cfg
}
func makePubsubClient(ctx context.Context, projectID string) pubsub.Client {
client, err := pubsub.NewClient(ctx, projectID)
handleError(err, "pubsub.NewClient")
return *client
}
func stageTopic(cfg Config) (context.Context, *pubsub.Topic) {
ctx := context.Background()
client := makePubsubClient(ctx, cfg.ProjectID)
topic := client.Topic(cfg.Topic)
return ctx, topic
}
func prepareMessage(msg *string) pubsub.Message {
message := pubsub.Message{Data: []byte(*msg)}
return message
}
func publishMessage(ctx context.Context, message *pubsub.Message, topic *pubsub.Topic) *pubsub.PublishResult {
result := topic.Publish(ctx, message)
return result
}
func printPublishResult(ctx context.Context, result *pubsub.PublishResult) {
id, err := result.Get(ctx)
handleError(err, "result.Get")
fmt.Println("Published message id: ", id)
}
var argMsg = flag.String("m", "Default message", "Message for Cloud PubSub. ")
func main() {
path := "cfg.json"
cfg := readConfig(&path)
ctx, topic := stageTopic(cfg)
defer topic.Stop()
flag.Parse()
msg := prepareMessage(argMsg)
result := publishMessage(ctx, &msg, topic)
printPublishResult(ctx, result)
}