Skip to content

Instantly share code, notes, and snippets.

@rickcrawford
Created November 27, 2017 03:42
Show Gist options
  • Save rickcrawford/fefc33e00d1994daa1fcff842784a8f3 to your computer and use it in GitHub Desktop.
Save rickcrawford/fefc33e00d1994daa1fcff842784a8f3 to your computer and use it in GitHub Desktop.
Create a GCS topic if it doesn't exist, then creates messages

Checks if a topic exists. If it doesn't it will be created. Next it will create messages on that topic with a new subscription.

package main

import (
	"context"
	"log"
	"time"

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

const projectID = "gcs-project-id"
const topicName = "my-topic-name"
const subscriptionName = "my-subscription-name"

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

	// Create a new topic with the given name.
	topic, err := client.CreateTopic(ctx, topicName)
	if err != nil {
		topic = client.Topic(topicName)
	}
	defer topic.Stop()

	// Create a new subscription to the previously created topic
	// with the given name.
	sub, err := client.CreateSubscription(ctx, subscriptionName, pubsub.SubscriptionConfig{
	  Topic:       topic,
	  AckDeadline: 10 * time.Second,
	})
  	if err != nil {
		sub = client.Subscription(subscriptionName)
	}

	go func() {
		for {

			res := topic.Publish(ctx, &pubsub.Message{Data: []byte("payload")})

			id, err := res.Get(ctx)
			if err != nil {
				log.Fatal("error publishing message", err)
			}
			log.Printf("Published a message with a message ID: %s\n", id)

			<-time.After(time.Second * 10)
		}

	}()

  // the following is blocking...
	log.Fatal(sub.Receive(context.Background(), func(ctx context.Context, m *pubsub.Message) {
	 	log.Printf("Got message: %s", m.Data)
	 	m.Ack()
	}))


}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment