How to Use Google Cloud Pub/Sub from Go

Web
Use the cloud.google.com/go/pubsub library to create topics and subscriptions, then publish and receive messages in Go.

Use the cloud.google.com/go/pubsub client library to create a topic, publish messages, create a subscription, and receive messages.

package main

import (
	"context"
	"fmt"
	"log"

	"cloud.google.com/go/pubsub"
)

func main() {
	ctx := context.Background()
	client, err := pubsub.NewClient(ctx, "project-id")
	if err != nil {
		log.Fatal(err)
	}
	defer client.Close()

	topic := client.Topic("my-topic")
	if _, err := topic.Create(ctx, nil); err != nil {
		log.Fatal(err)
	}

	result := topic.Publish(ctx, &pubsub.Message{Data: []byte("hello")})
	id, err := result.Get(ctx)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Published message with ID:", id)

	sub := client.Subscription("my-sub")
	if _, err := sub.Create(ctx, "my-topic", nil); err != nil {
		log.Fatal(err)
	}

	msg, err := sub.Receive(ctx, func(ctx context.Context, msg *pubsub.Message) {
		fmt.Println("Received:", string(msg.Data))
		msg.Ack()
	})
	if err != nil {
		log.Fatal(err)
	}
	_ = msg
}