tree: e9f87ae903a5ce92d7c2ed0b3510dac3b461231a [search]
  1. apiv1/
  2. internal/
  3. v2/
  4. CHANGES.md
  5. debug.go
  6. doc.go
  7. flow_controller.go
  8. iterator.go
  9. LICENSE
  10. message.go
  11. MIGRATING.md
  12. nodebug.go
  13. pubsub.go
  14. pullstream.go
  15. README.md
  16. schema.go
  17. service.go
  18. snapshot.go
  19. subscription.go
  20. topic.go
  21. trace.go
  22. transform.go
vendor/cloud.google.com/go/pubsub/README.md

Cloud Pub/Sub Go Reference

Example Usage

First create a pubsub.Client to use throughout your application:

client, err := pubsub.NewClient(ctx, "project-id")
if err != nil {
	log.Fatal(err)
}

Then use the client to publish and subscribe:

// Publish "hello world" on topic1.
topic := client.Topic("topic1")
res := topic.Publish(ctx, &pubsub.Message{
	Data: []byte("hello world"),
})
// The publish happens asynchronously.
// Later, you can get the result from res:
...
msgID, err := res.Get(ctx)
if err != nil {
	log.Fatal(err)
}

// Use a callback to receive messages via subscription1.
sub := client.Subscription("subscription1")
err = sub.Receive(ctx, func(ctx context.Context, m *pubsub.Message) {
	fmt.Println(m.Data)
	m.Ack() // Acknowledge that we've consumed the message.
})
if err != nil {
	log.Println(err)
}