Configuration API for Go SDK

Go complete API reference for building real-time applications on PubNub, including basic usage and sample code. View on GoDoc

Configuration

pubnub.Config stores settings that control the PubNub client. The configuration exposes properties to precisely configure client behavior.

Method(s)

Create a configuration instance with:

config := pubnub.NewConfigWithUserId(UserId)
* required
ParameterDescription
SubscribeKey *
Type: string
Default:
n/a
Subscribe key from the Admin Portal.
PublishKey
Type: string
Default:
None
Publish key from the Admin Portal (required if publishing).
SecretKey
Type: string
Default:
None
Secret key (only required for modifying or revealing access permissions).
SetUserId *
Type: UserId
Default:
n/a
userId to use. The UserId object takes String as an argument. You should set a unique identifier for the user or the device that connects to PubNub.

It's a UTF-8 encoded string of up to 92 alphanumeric characters.

If you don't set the userId, you won't be able to connect to PubNub.
AuthKey
Type: string
Default:
None
If Access Manager is utilized, the client uses this AuthKey in all restricted requests.
Secure
Type: bool
Default:
True
Use SSL.
MessageQueueOverflowCount
Type: int
Default:
100
Fires PNRequestMessageCountExceededCategory when a single subscribe response contains more than this many messages.
ConnectTimeout
Type: int
Default:
5
Maximum time to establish a connection, in seconds.
SubscribeRequestTimeout
Type: int
Default:
310
Subscribe request timeout, in seconds.
NonSubscribeRequestTimeout
Type: int
Default:
10
Non-subscribe request timeout, in seconds.
FilterExpression
Type: string
Default:
None
Feature to subscribe with a custom filter expression.
Origin
Type: string
Default:
ps.pndsn.com
Custom origin if needed.
To request a custom domain, contact support and follow the request process.
MaximumReconnectionRetries
Type: int
Default:
unlimited (-1)
The config sets how many times to retry to reconnect before giving up.
SetPresenceTimeout
Type: int
Default:
0
How long the server considers the client alive for presence. The client sends periodic heartbeats to stay active. If no heartbeat arrives within the timeout, the client is marked inactive and a "timeout" event is emitted on the presence channel.
SetPresenceTimeoutWithCustomInterval
Type: int
Default:
0
How often the client sends heartbeats. For shorter presence timeouts, set roughly to (SetPresenceTimeout / 2) - 1.
SuppressLeaveEvents
Type: bool
Default:
n/a
When true the SDK doesn't send out the leave requests.
MaxIdleConnsPerHost
Type: int
Default:
30
Used to set the value of HTTP Transport's MaxIdleConnsPerHost.
FileMessagePublishRetryLimit
Type: int
Default:
5
The number of tries made in case of Publish File Message failure.
CryptoModule
Type: crypto.NewAesCbcCryptor(CipherKey, UseRandomInitializationVector)

crypto.NewLegacyCryptor(CipherKey, UseRandomInitializationVector)
Default:
None
The cryptography module used for encryption and decryption of messages and files. Takes the CipherKey and UseRandomInitializationVector parameters as arguments.

For more information, refer to the CryptoModule section.
CipherKey
Type: string
Default:
None
This way of setting this parameter is deprecated, pass it to CryptoModule instead.

If CipherKey is passed, all communications to/from PubNub will be encrypted.
UseRandomInitializationVector
Type: bool
Default:
true
This way of setting this parameter is deprecated, pass it to CryptoModule instead.

When true the initialization vector (IV) is random for all requests (not just for file upload). When false the IV is hard-coded for all requests except for file upload.
UUID *
Type: string
Default:
n/a
This parameter is deprecated, use userId instead.

UUID to use. You should set a unique UUID to identify the user or the device that connects to PubNub.
If you don't set the UUID, you won't be able to connect to PubNub.
Disabling random initialization vector

Disable random initialization vector (IV) only for backward compatibility (<5.0.0) with existing applications. Never disable random IV on new applications.

CryptoModule

CryptoModule encrypts and decrypts messages and files. From 7.1.2, you can configure the algorithms it uses.

Each SDK includes two options: legacy 128‑bit encryption and recommended 256‑bit AES‑CBC. For background, see Message Encryption and File Encryption.

If you don't set CryptoModule but set cipherKey and useRandomInitializationVector in config, the client uses legacy encryption.

For configuration details, utilities, and examples, see Encryption.

Legacy encryption with 128-bit cipher key entropy

You don't have to change your encryption configuration if you want to keep using the legacy encryption. If you want to use the recommended 256 bit AES-CBC encryption, you must explicitly set that in PubNub config.

Sample code

Reference code
This example is a self-contained code snippet ready to be run. It includes necessary imports and executes methods with console logging. Use it as a reference when working with other examples in this document.
Required User ID

Always set the UserId to uniquely identify the user or device that connects to PubNub. This UserId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UserId, you won't be able to connect to PubNub.

package main

import (
"fmt"
crypto "github.com/pubnub/go/v7/crypto"
pubnub "github.com/pubnub/go/v7"
)

func main() {
// Configure the PubNub instance
config := pubnub.NewConfigWithUserId("myUniqueUserId")
config.SubscribeKey = "demo" // Use Demo keys for testing
config.PublishKey = "demo"
config.SecretKey = "mySecretKey"
config.Secure = true
show all 25 lines

Server response

Configured and ready to use client configuration instance.

Proxy configuration

The following sample configures a client to use a proxy for subscribe requests:

// Configure a proxy specifically for subscribe requests.
var pn *pubnub.PubNub
config = pubnub.NewConfigWithUserId(UserId("myUniqueUserId")
config.UseHTTP2 = false

pn = pubnub.NewPubNub(config)

transport := &http.Transport{
MaxIdleConnsPerHost: pn.Config.MaxIdleConnsPerHost,
Dial: (&net.Dialer{
Timeout: time.Duration(pn.Config.ConnectTimeout) * time.Second,
KeepAlive: 30 * time.Minute,
}).Dial,
ResponseHeaderTimeout: time.Duration(pn.Config.SubscribeRequestTimeout) * time.Second,
}
show all 25 lines

The following sample configures a client to use a proxy for non-subscribe requests:

// Configure a proxy for non-subscribe requests (publish, history, etc.).
var pn *pubnub.PubNub
config = pubnub.NewConfigWithUserId(UserId("myUniqueUserId")
config.UseHTTP2 = false

pn = pubnub.NewPubNub(config)

transport := &http.Transport{
MaxIdleConnsPerHost: pn.Config.MaxIdleConnsPerHost,
Dial: (&net.Dialer{
Timeout: time.Duration(pn.Config.ConnectTimeout) * time.Second,
KeepAlive: 30 * time.Minute,
}).Dial,
ResponseHeaderTimeout: time.Duration(pn.Config.NonSubscribeRequestTimeout) * time.Second,
}
show all 25 lines

Initialization

Add PubNub to your project using one of the procedures defined in the Getting Started guide.

Description

Initialize the PubNub Client Application Programming Interface (API) context before calling any API. This sets account-level credentials such as PublishKey and SubscribeKey.

Method(s)

Initialize PubNub with:

pn := pubnub.NewPubNub(config)
* required
ParameterDescription
config *
Type: Config
Goto Configuration for more details.

Sample code

Initialize the PubNub client API

Required User ID

Always set the UserId to uniquely identify the user or device that connects to PubNub. This UserId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UserId, you won't be able to connect to PubNub.

package main

import (
"fmt"

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

func main() {
// Configuration
config := pubnub.NewConfigWithUserId("myUniqueUserId")
config.SubscribeKey = "demo"
config.PublishKey = "demo"

// Initialize the PubNub instance
show all 19 lines

Returns

Returns the PubNub instance to call APIs such as Publish(), Subscribe(), History(), and HereNow().

Other examples

Initialize a non-secure client

Required User ID

Always set the UserId to uniquely identify the user or device that connects to PubNub. This UserId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UserId, you won't be able to connect to PubNub.

import (
pubnub "github.com/pubnub/go"
)

config := pubnub.NewConfigWithUserId("userId")
config.PublishKey = "my-pub-key"
config.SubscribeKey = "my-sub-key"

pn := pubnub.NewPubNub(config)

Initialization for a read-only client

In the case where a client will only read messages and never publish to a channel, you can simply omit the PublishKey when initializing the client:

Required User ID

Always set the UserId to uniquely identify the user or device that connects to PubNub. This UserId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UserId, you won't be able to connect to PubNub.

import (
pubnub "github.com/pubnub/go"
)

config := pubnub.NewConfigWithUserId("userId")
config.SubscribeKey = "my-sub-key"

pn := pubnub.NewPubNub(config)

Event listeners

You can receive connectivity status, messages, and presence notifications via listeners.

Add listeners before calling the method.

Add listeners

import (
pubnub "github.com/pubnub/go"
)

listener := pubnub.NewListener()

go func() {
for {
select {
case signal := <-listener.Signal:
//Channel
fmt.Println(signal.Channel)
//Subscription
fmt.Println(signal.Subscription)
//Payload
show all 108 lines

Remove listeners

listener := pubnub.NewListener()

pn.AddListener(listener)

// some time later
pn.RemoveListener(listener)

Handling disconnects

import (
pubnub "github.com/pubnub/go"
)

go func() {
for {
select {
case status := <-listener.Status:
switch status.Category {
case pubnub.PNDisconnectedCategory:
// handle disconnect here
}
case <-listener.Message:
case <-listener.Presence:
}
show all 17 lines

Listener status events

CategoryDescription
PNTimeoutCategory
Processing has failed because of request time out.
PNDisconnectedCategory
The SDK is not able to reach PubNub servers because the machine or device are not connected to Internet or this has been lost, your ISP (Internet Service Provider) is having to troubles or perhaps or the SDK is behind of a proxy.
PNConnectedCategory
SDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed).
PNAccessDeniedCategory
The SDK will announce this error when the Access Manager does not allow the subscription to a channel or a channel group.
PNBadRequestCategory
PubNub API server was unable to parse SDK request correctly.
PNCancelledCategory
Request was cancelled by user.
PNLoopStopCategory
Subscription loop has been stopped due some reasons.
PNReconnectedCategory
Subscription loop has been reconnected due some reasons.
PNAcknowledgmentCategory
An API call was successful. This status has additional details based on the type of the successful operation.
PNReconnectionAttemptsExhausted
The SDK loop has been stopped due maximum reconnection exhausted.
PNNoStubMatchedCategory/PNUnknownCategory
PNNoStubMatchedCategory as the StatusCategory means an unknown status category event occurred.
PNRequestMessageCountExceededCategory
PNRequestMessageCountExceededCategory is fired when the MessageQueueOverflowCount limit is exceeded by the number of messages received in a single subscribe request.

User ID

Use these functions to set or get a user ID at runtime.

Method(s)

Set or get UserId with:

config.SetUserId(UserId(string))
* required
ParameterDescription
UserId *
Type: string
Default:
n/a
UserId to be used as a device identifier. If you don't set the UserId, you won't be able to connect to PubNub.
config.GetUserId()

This method doesn't take any arguments.

Sample code

Set user ID

Required User ID

Always set the UserId to uniquely identify the user or device that connects to PubNub. This UserId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UserId, you won't be able to connect to PubNub.

import (
pubnub "github.com/pubnub/go"
)

config := pubnub.NewConfig()
config.SetUserId(UserId("myUniqueUserId"))

// set UserId in a single line
config := pubnub.NewConfigWithUserId("userId")

Get user ID

import (
pubnub "github.com/pubnub/go"
)

config := pubnub.NewConfig()

fmt.Println(config.GetUserId)

Authentication key

Set or get the user's authentication key.

Method(s)

config.AuthKey = string
* required
ParameterDescription
AuthKey *
Type: string
If Access Manager is utilized, client will use this AuthKey in all restricted requests.
config.AuthKey

This method doesn't take any arguments.

Sample code

Set auth key

import (
pubnub "github.com/pubnub/go"
)

config := pubnub.NewConfig()

config.AuthKey = "my_newauthkey"

Get auth key

fmt.Println(config.AuthKey)

Returns

None.

Filter expression

Requires Stream Controller add-on

This method requires that the Stream Controller add-on is enabled for your key in the Admin Portal. Read the support page on enabling add-on features on your keys.

Stream filtering lets a subscriber receive only messages that match a filter expression. The client sets the filter, and the server applies it to prevent unmatched messages from reaching the subscriber.

To set or get message filters, you can use the following methods. To learn more about filtering, refer to the Publish Messages documentation.

Method(s)

config.FilterExpression = string
* required
ParameterDescription
filterExpression *
Type: string
PSV2 feature to Subscribe with a custom filter expression.
config.FilterExpression

This method doesn't take any arguments.

Sample code

Set filter expression

Required User ID

Always set the UserId to uniquely identify the user or device that connects to PubNub. This UserId should be persisted, and should remain unchanged for the lifetime of the user or the device. If you don't set the UserId, you won't be able to connect to PubNub.

import (
pubnub "github.com/pubnub/go"
)

config := pubnub.NewConfig()

config.FilterExpression = "such=wow"

Get filter expression

fmt.Println(config.FilterExpression)
Last updated on