-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
54 lines (45 loc) · 1.22 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
package main
import (
"context"
"fmt"
"log"
"os"
"sync/atomic"
"time"
"cloud.google.com/go/pubsub"
"google.golang.org/api/option"
)
func main() {
projectID := os.Getenv("GOOGLE_CLOUD_PROJECT")
if projectID == "" {
fmt.Println("GOOGLE_CLOUD_PROJECT environment variable must be set.")
os.Exit(1)
}
subscription := os.Getenv("SUBSCRIPTION")
if subscription == "" {
fmt.Println("SUBSCRIPTION environment variable must be set to an existing Subscription.")
os.Exit(1)
}
ctx := context.Background()
client, err := pubsub.NewClient(ctx, projectID, option.WithCredentialsFile("/tmp/sa_credentials.json"))
if err != nil {
log.Fatal(err)
}
defer client.Close()
sub := client.Subscription(subscription)
// Receive messages for 10 seconds, which simplifies testing.
// Comment this out in production, since `Receive` should
// be used as a long running operation.
ctx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
var received int32
err = sub.Receive(ctx, func(_ context.Context, msg *pubsub.Message) {
fmt.Printf("Got message: %q\n", string(msg.Data))
atomic.AddInt32(&received, 1)
msg.Ack()
})
if err != nil {
fmt.Println(err)
}
fmt.Printf("Received %d messages\n", received)
}