Debian Codegraph @

samples/gocdk-pubsub/main.go

raw
1 // Copyright 2018 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // gocdk-pubsub demonstrates the use of the Go CDK pubsub package in a
16 // simple command-line application.
17 package main
18
19 import (
20 "bufio"
21 "context"
22 "flag"
23 "fmt"
24 "log"
25 "os"
26
27 "github.com/google/subcommands"
28 "gocloud.dev/pubsub"
29
30 // Import the pubsub driver packages we want to be able to open.
31 _ "gocloud.dev/pubsub/awssnssqs"
32 _ "gocloud.dev/pubsub/azuresb"
33 _ "gocloud.dev/pubsub/gcppubsub"
34 _ "gocloud.dev/pubsub/kafkapubsub"
35 _ "gocloud.dev/pubsub/natspubsub"
36 _ "gocloud.dev/pubsub/rabbitpubsub"
37 )
38
39 const helpSuffix = `
40
41 See https://gocloud.dev/concepts/urls/ for more background on
42 Go CDK URLs, and sub-packages under gocloud.dev/pubsub
43 (https://godoc.org/gocloud.dev/pubsub#pkg-subdirectories)
44 for details on the topic/subscription URL format.
45 `
46
47 func main() {
48 os.Exit(run())
49 }
50
51 func run() int {
52 subcommands.Register(subcommands.HelpCommand(), "")
53 subcommands.Register(&pubCmd{}, "")
54 subcommands.Register(&subCmd{}, "")
55 log.SetFlags(0)
56 log.SetPrefix("gocdk-pubsub: ")
57 flag.Parse()
58 return int(subcommands.Execute(context.Background()))
59 }
60
61 type pubCmd struct{}
62
63 func (*pubCmd) Name() string { return "pub" }
64 func (*pubCmd) Synopsis() string { return "Publish a message to a topic" }
65 func (*pubCmd) Usage() string {
66 return `pub <topic URL>
67
68 Read messages from stdin, one per line and send them to <topic URL>.
69
70 Example:
71 gocdk-pubsub pub gcppubsub://myproject/mytopic` + helpSuffix
72 }
73
74 func (*pubCmd) SetFlags(_ *flag.FlagSet) {}
75
76 func (*pubCmd) Execute(ctx context.Context, f *flag.FlagSet, _ ...any) subcommands.ExitStatus {
77 if f.NArg() != 1 {
78 f.Usage()
79 return subcommands.ExitUsageError
80 }
81 topicURL := f.Arg(0)
82
83 // Open a *pubsub.Topic using the URL.
84 topic, err := pubsub.OpenTopic(ctx, topicURL)
85 if err != nil {
86 log.Print(err)
87 return subcommands.ExitFailure
88 }
89 defer topic.Shutdown(ctx)
90
91 // Read lines from stdin and send them as messages to the topic.
92 fmt.Fprintf(os.Stderr, "Enter messages, one per line, to be published to %q.\n", topicURL)
93 scanner := bufio.NewScanner(os.Stdin)
94 for scanner.Scan() {
95 line := scanner.Text()
96 if line == "" {
97 log.Print("Skipping empty message.")
98 continue
99 }
100 m := &pubsub.Message{Body: []byte(line)}
101 if err := topic.Send(ctx, m); err != nil {
102 log.Print(err)
103 return subcommands.ExitFailure
104 }
105 }
106 if err := scanner.Err(); err != nil {
107 log.Print(err)
108 return subcommands.ExitFailure
109 }
110 return subcommands.ExitSuccess
111 }
112
113 type subCmd struct {
114 n int // number of messages to receive, or 0 for infinite
115 }
116
117 func (*subCmd) Name() string { return "sub" }
118 func (*subCmd) Synopsis() string { return "Receive messages from a subscription" }
119 func (*subCmd) Usage() string {
120 return `sub [-n N] <subscription URL>
121
122 Receive messages from <subscription URL> and send them to stdout, one per line.
123
124 Example:
125 gocdk-pubsub sub gcppubsub://myproject/mytopic` + helpSuffix
126 }
127
128 func (cmd *subCmd) SetFlags(f *flag.FlagSet) {
129 f.IntVar(&cmd.n, "n", 0, "number of messages to receive, or 0 for unlimited")
130 }
131
132 func (cmd *subCmd) Execute(ctx context.Context, f *flag.FlagSet, _ ...any) subcommands.ExitStatus {
133 if f.NArg() != 1 {
134 f.Usage()
135 return subcommands.ExitUsageError
136 }
137 subURL := f.Arg(0)
138
139 // Open a *pubsub.Subscription using the URL.
140 sub, err := pubsub.OpenSubscription(ctx, subURL)
141 if err != nil {
142 log.Print(err)
143 return subcommands.ExitFailure
144 }
145 defer sub.Shutdown(ctx)
146
147 // Receive messages from the subscription and print them to stdout.
148 fmt.Printf("Receiving messages from %q...\n", subURL)
149 for i := 0; cmd.n == 0 || i < cmd.n; i++ {
150 m, err := sub.Receive(ctx)
151 if err != nil {
152 log.Print(err)
153 return subcommands.ExitFailure
154 }
155 fmt.Printf("%s\n", m.Body)
156 m.Ack()
157 }
158 return subcommands.ExitSuccess
159 }