---
source_url: https://www.pubnub.com/docs/sdks/go
title: Go API & SDK Docs v8.1.0
updated_at: 2026-05-22T11:06:37.308Z
sdk_name: PubNub Go SDK
sdk_version: v8.1.0
---

> Documentation Index
> For a curated overview of PubNub documentation, see: https://www.pubnub.com/docs/llms.txt
> For the full list of all documentation pages, see: https://www.pubnub.com/docs/llms-full.txt


# Go API & SDK Docs v8.1.0

PubNub Go SDK, use the latest version: v8.1.0

Install:

```bash
go get github.com/pubnub/go/v8@v8.1.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](https://admin.pubnub.com/#/login) or [create an account](https://admin.pubnub.com/#/signup) 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

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

###### go get

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

```bash
go get github.com/pubnub/go/v8
```

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

###### go.mod

For projects using Go modules, add the dependency to your `go.mod` file:

```go
require github.com/pubnub/go/v8 v8.1.0
```

Then run:

```bash
go mod tidy
```

###### Source code

Clone the [GitHub repository](https://github.com/pubnub/go):

```bash
git clone https://github.com/pubnub/go.git
```

View the [supported platforms](https://www.pubnub.com/docs/sdks/go/platform-support) 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.

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"
	"time"

	pubnub "github.com/pubnub/go/v8"
)

// Example_init demonstrates PubNub initialization
func Example_init() {
	// Create configuration with a unique user ID
	config := pubnub.NewConfigWithUserId(pubnub.UserId("my-user-id"))

	// Set your PubNub keys
	config.SubscribeKey = "demo" // Replace with your subscribe key
	config.PublishKey = "demo"   // Replace with your publish key

	// Initialize PubNub client
	pn := pubnub.NewPubNub(config)

	if pn != nil {
		fmt.Println("PubNub client initialized successfully")
	}
}
```

For more information, refer to the [Configuration](https://www.pubnub.com/docs/sdks/go/api-reference/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:

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"
	"time"

	pubnub "github.com/pubnub/go/v8"
)

// Example_set_up_listeners demonstrates setting up listeners
func Example_setUpListeners() {
	// snippet.hide
	config := pubnub.NewConfigWithUserId(pubnub.UserId("my-user-id"))
	pn := pubnub.NewPubNub(config)
	// snippet.show

	// Create a listener
	listener := pubnub.NewListener()

	// Create channel to signal connection event
	doneConnect := make(chan bool)

	// Create quit channel for goroutine cleanup
	quit := make(chan bool)

	// Start a goroutine to process events
	go func() {
		for {
			select {
			case status := <-listener.Status:
				// Handle status events
				switch status.Category {
				case pubnub.PNConnectedCategory:
					// Connected to the PubNub network
					fmt.Println("Connected to PubNub!")
					doneConnect <- true
				case pubnub.PNDisconnectedCategory:
					// Disconnected from the PubNub network
					fmt.Println("Disconnected from PubNub!")
				case pubnub.PNReconnectedCategory:
					// Reconnected to the PubNub network
					fmt.Println("Reconnected to PubNub!")
				}

			case message := <-listener.Message:
				// Handle new message
				fmt.Println("Received message:", message.Message)

			case presence := <-listener.Presence:
				// Handle presence
				fmt.Println("Presence event:", presence.Event)

			case <-quit:
				// Exit goroutine when function returns
				return
			}
		}
	}()

	// Add the listener to PubNub
	pn.AddListener(listener)

	// When don't need to listen to events anymore, close the quit channel to exit the goroutine
	close(quit)
}
```

For more information, refer to the [Listeners](https://www.pubnub.com/docs/sdks/go/api-reference/configuration#event-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:

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"
	"time"

	pubnub "github.com/pubnub/go/v8"
)

// Example_createSubscription demonstrates creating a subscription
func Example_createSubscription() {
	// snippet.hide
	config := pubnub.NewConfigWithUserId(pubnub.UserId("my-user-id"))
	pn := pubnub.NewPubNub(config)
	doneConnect := make(chan bool)
	// snippet.show

	// Define the channel you want to subscribe to
	channel := "my-channel"

	// Subscribe to the channel
	pn.Subscribe().
		Channels([]string{channel}).
		Execute()

	<-doneConnect

	fmt.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](https://www.pubnub.com/docs/sdks/go/api-reference/publish-and-subscribe#subscribe) section of the SDK documentation.

```go
// Replace with your package name (usually "main")
package pubnub_samples_test

import (
	"fmt"
	"time"

	pubnub "github.com/pubnub/go/v8"
)

// Example_publishMessage demonstrates publishing a message
func Example_publishMessage() {
	// snippet.hide
	config := pubnub.NewConfigWithUserId(pubnub.UserId("my-user-id"))
	pn := pubnub.NewPubNub(config)
	channel := "my-channel"
	// snippet.show

	// Create a message
	message := map[string]interface{}{
		"text":   "Hello, world!",
		"sender": "go-sdk",
	}

	fmt.Println("Publishing message:", message)

	// Publish the message to the channel
	response, _, err := pn.Publish().
		Channel(channel).
		Message(message).
		Execute()

	if err != nil {
		// Handle publish error
		fmt.Println("Publish error:", err)
	} else {
		// Handle successful publish
		fmt.Println("Publish successful! Timetoken:", response.Timestamp)
	}
}
```

### Run the app

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

```bash
go run pubnub_example.go
```

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

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

## Complete example

```go
// Example_completeExample demonstrates a complete PubNub workflow: initialize, subscribe, and publish
func Example_completeExample() {

	// Step 1: Initialize PubNub with configuration
	config := pubnub.NewConfigWithUserId(pubnub.UserId("go-user"))
	config.SubscribeKey = "demo" // Replace with your subscribe key
	config.PublishKey = "demo"   // Replace with your publish key

	// snippet.hide
	config = setPubnubExampleConfigData(config)
	// snippet.show

	pn := pubnub.NewPubNub(config)
	fmt.Println("PubNub instance initialized")

	// Step 2: Create channel to signal connection event
	doneConnect := make(chan bool)
	listener := pubnub.NewListener()

	// Create quit channel for goroutine cleanup
	quit := make(chan bool)

	// Step 3: Set up listener for events
	go func() {
		for {
			select {
			case status := <-listener.Status:
				// Handle status events
				switch status.Category {
				case pubnub.PNConnectedCategory:
					// Connected to the PubNub network
					fmt.Println("Connected to PubNub!")
					doneConnect <- true
				case pubnub.PNDisconnectedCategory:
					// Disconnected from the PubNub network
					fmt.Println("Disconnected from PubNub!")
				case pubnub.PNReconnectedCategory:
					// Reconnected to the PubNub network
					fmt.Println("Reconnected to PubNub!")
				}

			case message := <-listener.Message:
				// Handle new message
				fmt.Println("Received message:", message.Message)

			case presence := <-listener.Presence:
				// Handle presence
				fmt.Println("Presence event:", presence.Event)

			case <-quit:
				// Exit goroutine when function returns
				return
			}
		}
	}()

	// Add the listener to PubNub
	pn.AddListener(listener)

	// Step 4: Define the channel and subscribe
	channel := "my-channel"
	pn.Subscribe().
		Channels([]string{channel}).
		Execute()

	// Wait for connection to establish
	<-doneConnect
	fmt.Println("Subscribed to channel:", channel)

	// Optional: Wait a moment to ensure subscription is fully set up
	time.Sleep(1 * time.Second)

	// Step 5: Create and publish a message
	message := map[string]interface{}{
		"text":   "Hello, world!",
		"sender": "go-sdk",
	}

	fmt.Println("Publishing message:", message)

	// Publish the message
	_, _, err := pn.Publish().
		Channel(channel).
		Message(message).
		Execute()

	if err != nil {
		fmt.Println("Publish error:", err)
	} else {
		fmt.Println("Publish successful!")
	}

	// Wait for the message to be received
	time.Sleep(3 * time.Second)

	// Step 6: Clean up
	pn.UnsubscribeAll()
	close(quit)
	fmt.Println("Example completed successfully!")

}
```

### Troubleshooting

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

| Issue | Possible 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:

### Realtime features

* Set up [Presence](https://www.pubnub.com/docs/sdks/go/api-reference/presence) to track who's online
* Implement [channel groups](https://www.pubnub.com/docs/sdks/go/api-reference/channel-groups) to organize your channels
* Use [Signals](https://www.pubnub.com/docs/sdks/go/api-reference/publish-and-subscribe#signal) for lightweight notifications

### Advanced features

* Try out [Access Manager](https://www.pubnub.com/docs/sdks/go/api-reference/access-manager) to secure your channels
* Implement [Message Persistence](https://www.pubnub.com/docs/sdks/go/api-reference/storage-and-playback) to store and retrieve messages
* Use [Push Notifications](https://www.pubnub.com/docs/sdks/go/api-reference/mobile-push) for mobile devices

### Real examples

* [Build a chat app in Go](https://www.pubnub.com/blog/build-a-chat-app-in-go-using-pubnub/)
* Explore our [GitHub repository](https://github.com/pubnub/go) for more code samples

### More help

* Check out our [SDK reference documentation](https://www.pubnub.com/docs/sdks/go/api-reference/configuration) for detailed API information
* Visit our [support portal](https://support.pubnub.com/) for additional resources
* Ask our AI assistant (the looking glass icon at the top of the page) for help

## Terms in this document

* **Publish Key** - A unique identifier that allows your application to send messages to PubNub channels. It's part of your app's credentials and should be kept secure.
* **PubNub** - PubNub is a real-time messaging platform that provides APIs and SDKs for building scalable applications. It handles the complex infrastructure of real-time communication, including: Message delivery and persistence, Presence detection, Access control, Push notifications, File sharing, Serverless processing with Functions and Events & Actions, Analytics and monitoring with BizOps Workspace, AI-powered insights with Illuminate.
* **Subscribe Key** - A unique identifier that allows your application to receive messages from PubNub channels. It's part of your app's credentials and should be kept secure.