forked from GoogleCloudPlatform/golang-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
231 lines (205 loc) · 5.41 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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
// Copyright 2016 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.
// Command subscriptions is a tool to manage Google Cloud Pub/Sub subscriptions by using the Pub/Sub API.
// See more about Google Cloud Pub/Sub at https://cloud.google.com/pubsub/docs/overview.
package main
import (
"fmt"
"log"
"os"
"sync"
"time"
// [START imports]
"golang.org/x/net/context"
"cloud.google.com/go/iam"
"cloud.google.com/go/pubsub"
"google.golang.org/api/iterator"
// [END imports]
)
func main() {
ctx := context.Background()
// [START auth]
proj := os.Getenv("GOOGLE_CLOUD_PROJECT")
if proj == "" {
fmt.Fprintf(os.Stderr, "GOOGLE_CLOUD_PROJECT environment variable must be set.\n")
os.Exit(1)
}
client, err := pubsub.NewClient(ctx, proj)
if err != nil {
log.Fatalf("Could not create pubsub Client: %v", err)
}
// [END auth]
// Print all the subscriptions in the project.
fmt.Println("Listing all subscriptions from the project:")
subs, err := list(client)
if err != nil {
log.Fatal(err)
}
for _, sub := range subs {
fmt.Println(sub)
}
t := createTopicIfNotExists(client)
const sub = "example-subscription"
// Create a new subscription.
if err := create(client, sub, t); err != nil {
log.Fatal(err)
}
// Pull messages via the subscription.
if err := pullMsgs(client, sub, t); err != nil {
log.Fatal(err)
}
// Delete the subscription.
if err := delete(client, sub); err != nil {
log.Fatal(err)
}
}
func list(client *pubsub.Client) ([]*pubsub.Subscription, error) {
ctx := context.Background()
// [START get_all_subscriptions]
var subs []*pubsub.Subscription
it := client.Subscriptions(ctx)
for {
s, err := it.Next()
if err == iterator.Done {
break
}
if err != nil {
return nil, err
}
subs = append(subs, s)
}
// [END get_all_subscriptions]
return subs, nil
}
func pullMsgs(client *pubsub.Client, name string, topic *pubsub.Topic) error {
ctx := context.Background()
// Publish 10 messages on the topic.
var results []*pubsub.PublishResult
for i := 0; i < 10; i++ {
res := topic.Publish(ctx, &pubsub.Message{
Data: []byte(fmt.Sprintf("hello world #%d", i)),
})
results = append(results, res)
}
// Check that all messages were published.
for _, r := range results {
_, err := r.Get(ctx)
if err != nil {
return err
}
}
// [START pull_messages]
// Consume 10 messages.
var mu sync.Mutex
received := 0
sub := client.Subscription(name)
cctx, cancel := context.WithCancel(ctx)
err := sub.Receive(cctx, func(ctx context.Context, msg *pubsub.Message) {
mu.Lock()
defer mu.Unlock()
if received >= 10 {
cancel()
msg.Nack()
return
}
fmt.Printf("Got message: %q\n", string(msg.Data))
received++
msg.Ack()
})
if err != nil {
return err
}
// [END pull_messages]
return nil
}
func create(client *pubsub.Client, name string, topic *pubsub.Topic) error {
ctx := context.Background()
// [START create_subscription]
sub, err := client.CreateSubscription(ctx, name, topic, 20*time.Second, nil)
if err != nil {
return err
}
fmt.Printf("Created subscription: %v\n", sub)
// [END create_subscription]
return nil
}
func delete(client *pubsub.Client, name string) error {
ctx := context.Background()
// [START delete_subscription]
sub := client.Subscription(name)
if err := sub.Delete(ctx); err != nil {
return err
}
fmt.Println("Subscription deleted.")
// [END delete_subscription]
return nil
}
func createTopicIfNotExists(c *pubsub.Client) *pubsub.Topic {
ctx := context.Background()
const topic = "example-topic"
// Create a topic to subscribe to.
t := c.Topic(topic)
ok, err := t.Exists(ctx)
if err != nil {
log.Fatal(err)
}
if ok {
return t
}
t, err = c.CreateTopic(ctx, topic)
if err != nil {
log.Fatalf("Failed to create the topic: %v", err)
}
return t
}
func getPolicy(c *pubsub.Client, subName string) *iam.Policy {
ctx := context.Background()
// [START pubsub_get_subscription_policy]
policy, err := c.Subscription(subName).IAM().Policy(ctx)
if err != nil {
log.Fatal(err)
}
for _, role := range policy.Roles() {
log.Printf("%q: %q", role, policy.Members(role))
}
// [END pubsub_get_subscription_policy]
return policy
}
func addUsers(c *pubsub.Client, subName string) {
ctx := context.Background()
// [START pubsub_set_subscription_policy]
sub := c.Subscription(subName)
policy, err := sub.IAM().Policy(ctx)
if err != nil {
log.Fatalf("GetPolicy: %v", err)
}
// Other valid prefixes are "serviceAccount:", "user:"
// See the documentation for more values.
policy.Add(iam.AllUsers, iam.Viewer)
policy.Add("group:cloud-logs@google.com", iam.Editor)
if err := sub.IAM().SetPolicy(ctx, policy); err != nil {
log.Fatalf("SetUser: %v", err)
}
// NOTE: It may be necessary to retry this operation if IAM policies are
// being modified concurrently. SetPolicy will return an error if the policy
// was modified since it was retrieved.
// [END pubsub_set_subscription_policy]
}
func testPermissions(c *pubsub.Client, subName string) []string {
ctx := context.Background()
// [START pubsub_test_subscription_permissions]
sub := c.Subscription(subName)
perms, err := sub.IAM().TestPermissions(ctx, []string{
"pubsub.subscriptions.consume",
"pubsub.subscriptions.update",
})
if err != nil {
log.Fatal(err)
}
for _, perm := range perms {
log.Printf("Allowed: %v", perm)
}
// [END pubsub_test_subscription_permissions]
return perms
}