Go API & SDK Docs v7.4.0

This guide walks you through a simple "Hello, World" application that demonstrates the core concepts of PubNub:

  • Setting up a connection
  • Sending messages
  • Receiving messages in real-time

Overview

This guide helps you get up and running with PubNub in your Go application. The Go software development kit (SDK) provides a simple interface for integrating PubNub real-time messaging into your Go applications.

Go's concurrency model with goroutines and channels makes it an excellent choice for building real-time applications that can handle many connections efficiently. Whether you're building a web service, CLI application, or backend system, this guide will show you how to get started with PubNub in Go.

Prerequisites

Before we dive in, make sure you have:

  • A basic understanding of Go programming
  • Go installed on your machine (version 1.11 or later)
  • Your preferred Go IDE or text editor
  • A PubNub account (we'll help you set this up!)

Setup

Get your PubNub keys

First, get your PubNub keys:

  • Sign in or create an account on the PubNub Admin Portal.
  • Create an app (or use an existing one).
  • Find your publish and subscribe keys in the app dashboard.

When you create an app, PubNub automatically generates a keyset. You can use the same keyset for development and production, but we recommend separate keysets for each environment to improve security and management.

Install the SDK

SDK version

Always use the latest SDK version to have access to the newest features and avoid security vulnerabilities, bugs, and performance issues.

To integrate PubNub into your Go project using the go get command:

1go get github.com/pubnub/go/v7

If you encounter dependency issues, use the go mod tidy command to resolve them.

View the supported platforms for more information about compatibility.

Steps

Initialize PubNub

In your Go project, create a new file named pubnub_example.go with the following content. This is the minimum configuration you need to send and receive messages with PubNub.

Make sure to replace the demo keys with your app's publish and subscribe keys from the Admin Portal.

1// Import required packages
2package main
3
4import (
5 "fmt"
6
7 pubnub "github.com/pubnub/go/v7"
8)
9
10func main() {
11 // Set up PubNub configuration
12 config := pubnub.NewConfigWithUserId("go-user")
13 config.SubscribeKey = "demo" // Replace with your subscribe key
14 config.PublishKey = "demo" // Replace with your publish key
15
show all 21 lines

For more information, refer to the Configuration section of the SDK documentation.

Set up event listeners

Listeners help your application react to events and messages. You can implement custom logic to respond to each type of message or event.

In Go, we use channels to handle asynchronous events. Let's set up listeners for status updates and incoming messages:

1// Create a listener
2listener := pubnub.NewListener()
3
4// Create channels to signal events
5doneConnect := make(chan bool)
6donePublish := make(chan bool)
7
8// Start a goroutine to process events
9go func() {
10 for {
11 select {
12 case status := <-listener.Status:
13 // Handle status events
14 switch status.Category {
15 case pubnub.PNConnectedCategory:
show all 42 lines

For more information, refer to the Listeners section of the SDK documentation.

Create a subscription

To receive messages sent to a particular channel, you need to subscribe to it. This allows you to receive messages published to that channel in real-time:

1// Define the channel you want to subscribe to
2channel := "my-channel"
3
4// Subscribe to the channel
5pn.Subscribe().
6 Channels([]string{channel}).
7 Execute()
8
9// Wait for the connection to establish
10<-doneConnect
11fmt.Println("Subscribed to channel:", channel)

Publish messages

When you publish a message to a channel, PubNub delivers that message to everyone who is subscribed to that channel.

A message can be any type of JavaScript Object Notation (JSON)-serializable data (such as objects, arrays, integers, strings) that is smaller than 32 KiB.

For more information, refer to the Subscribe section of the SDK documentation.

1// Create a message
2message := map[string]interface{}{
3 "text": "Hello, world!",
4 "sender": "go-sdk",
5}
6
7fmt.Println("Publishing message:", message)
8
9// Publish the message to the channel
10response, _, err := pn.Publish().
11 Channel(channel).
12 Message(message).
13 Execute()
14
15if err != nil {
show all 24 lines

Run the app

To test your Go application, save the file and run it using:

go run pubnub_example.go

When you run the application, you should see output similar to the following:

1PubNub instance initialized
2Connected to PubNub!
3Subscribed to channel: my-channel
4Publishing message: map[sender:go-sdk text:Hello, world!]
5Publish successful! Timetoken: 16967543908123456
6Received message: map[sender:go-sdk text:Hello, world!]

Complete example

1package main
2
3import (
4 "fmt"
5 "time"
6
7 pubnub "github.com/pubnub/go/v7"
8)
9
10func main() {
11 // Step 1: Initialize PubNub with configuration
12 config := pubnub.NewConfigWithUserId("go-user")
13 config.SubscribeKey = "demo" // Replace with your subscribe key
14 config.PublishKey = "demo" // Replace with your publish key
15
show all 91 lines

Troubleshooting

If you don't see the expected output, here are some common issues and how to fix them:

IssuePossible Solutions
No connection message
  • Check your internet connection.
  • Verify your publish and subscribe keys are correct.
  • Make sure you're not behind a firewall blocking PubNub's connections.
Message not received
  • Double-check that you're subscribed to the correct channel.
  • Verify that the message was actually sent (check for any error messages).
  • Make sure you're waiting long enough for the message to be delivered.
Build errors
  • Ensure your Go version is up to date.
  • Run go mod tidy to fix dependency issues.
  • Make sure all imports are correct.

Next steps

Great job! 🎉 You've successfully created your first PubNub application with Go. Here are some exciting things you can explore next:

Last updated on