- About Pub/Sub Lite
- Client library documentation
- API documentation
- Go client documentation
- Complete sample programs
This library is in BETA. Backwards-incompatible changes may be made before stable v1.0.0 is released.
import (
"cloud.google.com/go/pubsub"
"cloud.google.com/go/pubsublite/pscompat"
)
To publish messages to a topic:
// Create a PublisherClient for topic1 in zone us-central1-b.
// See https://cloud.google.com/pubsub/lite/docs/locations for available zones.
const topic = "projects/project-id/locations/us-central1-b/topics/topic1"
publisher, err := pscompat.NewPublisherClient(ctx, topic)
if err != nil {
log.Fatal(err)
}
// Publish "hello world".
res := publisher.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)
}
To receive messages for a subscription:
// Create a SubscriberClient for subscription1 in zone us-central1-b.
const subscription = "projects/project-id/locations/us-central1-b/subscriptions/subscription1"
subscriber, err := pscompat.NewSubscriberClient(ctx, subscription)
if err != nil {
log.Fatal(err)
}
// Use a callback to receive messages.
// Call cancel() to stop receiving messages.
cctx, cancel := context.WithCancel(ctx)
err = subscriber.Receive(cctx, 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)
}