Implementation of Google Cloud Pub/Sub Publisher

Learn how to implement Google Cloud Pub/Sub Publisher in Golang

ta-ching chen

2 minute read

 Table of Contents



Clone Repo 

Now lets get into the hands-on!

# Clone repo and restore dependencies
$ git clone \

restore dependencies with godep

$ go get -u
$ cd $GOPATH/src/ && godep restore


Try to run the Publisher before we dig into the code.

$ GOOGLE_CLOUD_PROJECT="<your google project name>" go run publisher.go
$ GOOGLE_CLOUD_PROJECT="test-project" go run publisher.go
2017/01/04 01:04:21 4d27aaba-e62b-49cf-8fd9-e784a99064d5 send
2017/01/04 01:04:22 48b04306-18de-44f2-b1b3-c0e736f52d32 send
2017/01/04 01:04:24 d395cd6b-02ef-4e7d-a6ec-a84d0cf27045 send
2017/01/04 01:04:25 a56991b0-b664-48d7-8901-de80783f182d send
2017/01/04 01:04:26 d0cebf2f-619c-4642-b51b-d5485fd072c2 send
2017/01/04 01:04:28 46d25e6d-0f6b-4dc9-be88-8133e2a011e1 send
2017/01/04 01:04:29 dc517460-dc5b-4f61-ab20-490c186360a9 send
2017/01/04 01:04:30 f1ed3359-125b-4931-b631-d251a2109dcd send
2017/01/04 01:04:31 eaf771ca-c8e3-40ef-a89e-429b6bf8f55a send
2017/01/04 01:04:32 fb8b201c-2856-4bed-ac1a-3fc27d51bdac send

You can see that the program sending out ten message to Pub/Sub,

but what exactly the Publisher do after we launched it?

In the previous post, we know that Publisher need to register a topic in Cloud Pub/Sub before sending messages. Once the Publisher is coming up, it first calls the function CreateTopicIfNotExists,then dispatch CreateTopic to create the topic we want.

// publisher.go
const topicName string = "example-topic"
topic := common.CreateTopicIfNotExists(client, topicName)
// common/functions.go
func CreateTopicIfNotExists(client *pubsub.Client, name string) *pubsub.Topic {
    ctx := context.Background()
    topic := client.Topic(name)
    isExist, err := topic.Exists(ctx)
    if err != nil {
    if isExist {
        return topic
    topic, err = client.CreateTopic(ctx, name)
    if err != nil {
        log.Fatalf("Failed to create topic: %v", err)
    return topic

Once the topic is created successfully,we can see it shows on the Pub/Sub console.

Pub/Sub Flow

After creating the topic, we create an instance of pubsub.Message type, brings our Json format message as payload in Data field and sends it to Pub/Sub.

// publisher.go
for i := 0; i < 10; i++ {
    msgUuid := uuid.NewV4().String()
    // message we want to send to subscriber
    session, _ := json.Marshal(&common.Session{
      SessionID: msgUuid,
      TimeStamp: time.Now().Unix(),
    // publish message to Cloud Pub/Sub
    _, _ = topic.Publish(ctx, &pubsub.Message{
      Data: session,
    log.Printf("%s send", msgUuid)
    time.Sleep(1 * time.Second)

That’s it! Publisher is quite easy to implement! Now, lets see how to implement the subscriber.

Further Readings 


comments powered by Disqus