Example #1
0
// Queue the message in the given topic
func (m *Message) Queue(topic *pubsub.Topic) error {
	data, err := json.Marshal(m)
	if err != nil {
		return err
	}
	msgIds, err := topic.Publish(context.Background(), &pubsub.Message{
		Data: data,
	})
	if err != nil {
		return err
	}

	glog.Infof("Published to topic (%s): %s", topic.String(), msgIds)

	return nil
}
func pullMsgs(client *pubsub.Client, name string, topic *pubsub.Topic) error {
	ctx := context.Background()

	// publish 10 messages on the topic.
	for i := 0; i < 10; i++ {
		_, err := topic.Publish(ctx, &pubsub.Message{
			Data: []byte(fmt.Sprintf("hello world #%d", i)),
		})
		if err != nil {
			return err
		}
	}

	// [START pull_messages]
	sub := client.Subscription(name)
	it, err := sub.Pull(ctx)
	if err != nil {
		return err
	}
	defer it.Stop()

	// Consume 10 messages.
	for i := 0; i < 10; i++ {
		msg, err := it.Next()
		if err == iterator.Done {
			break
		}
		if err != nil {
			return err
		}
		fmt.Printf("Got message: %q\n", string(msg.Data))
		msg.Done(true)
	}
	// [END pull_messages]
	return nil
}