Configuration API for PubNub Go SDK

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

Configuration

pubnub.Config instance is storage for user-provided information which describe further PubNub client behavior. Configuration instance contains additional set of properties which allow performing precise PubNub client configuration.

Method(s)

To create configuration instance you can use the following function in the Go V4 SDK:

config := pubnub.NewConfig()
ParameterTypeRequiredDefaultDescription
SubscribeKeystringYesSubscribeKey from Admin Portal.
PublishKeystringOptionalNonePublishKey from Admin Portal (only required if publishing).
SecretKeystringOptionalNoneSecretKey (only required for modifying/revealing access permissions).
CipherKeystringOptionalNoneIf CipherKey is passed, all communications to/from PubNub will be encrypted.
SetUserIdUserIdYesuserId 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 64 alphanumeric characters.

If you don't set the userId, you won't be able to connect to PubNub.
AuthKeystringOptionalNoneIf Access Manager is utilized, client will use this AuthKey in all restricted requests.
SecureboolOptionalTrueUse SSL.
MessageQueueOverflowCountintOptional100When the limit is exceeded by the number of messages received in a single subscribe request, a status event PNRequestMessageCountExceededCategory is fired.
ConnectTimeoutintOptional5How long to wait before giving up connection to client.The value is in seconds.
SubscribeRequestTimeoutintOptional310How long to keep the Subscribe loop running before disconnect.The value is in seconds.
NonSubscribeRequestTimeoutintOptional10On Non subscribe operations, how long to wait for server response.The value is in seconds.
FilterExpressionstringOptionalNoneFeature to subscribe with a custom filter expression.
OriginstringOptionalps.pndsn.comCustom Origin if needed.
MaximumReconnectionRetriesintOptionalunlimited (-1)The config sets how many times to retry to reconnect before giving up.
SetPresenceTimeoutintOptional0The setting with set the custom presence server timeout.The value is in seconds.
SetPresenceTimeoutWithCustomIntervalintOptional0The setting with set the custom presence server timeout along with the custom interval to send the ping back to the server.The value is in seconds.
SuppressLeaveEventsboolOptionalWhen true the SDK doesn't send out the leave requests.
MaxIdleConnsPerHostintOptional30Used to set the value of HTTP Transport's MaxIdleConnsPerHost.
FileMessagePublishRetryLimitintOptional5The number of tries made in case of Publish File Message failure.
UseRandomInitializationVectorboolOptionaltrueWhen 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.
UUIDstringYesThis 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.

Basic Usage

Required UserId

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.

config := pubnub.NewConfig()

// SubscribeKey from Admin Portal
config.SubscribeKey = "SubscribeKey" // required

// PublishKey from Admin Portal (only required if publishing)
config.PublishKey = "PublishKey"

// SecretKey (only required for access operations, keep away from Android)
config.SecretKey = "SecretKey"

// if CipherKey is passed, all communicatons to/from pubnub will be encrypted
config.CipherKey = "cipherKey"

// user ID to be used as a device identifier
show all 36 lines

Rest Response from Server

Configured and ready to use client configuration instance.

Proxy Configuration

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

var pn *pubnub.PubNub
config = pubnub.NewConfig()
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,
}
proxyURL, err := url.Parse(fmt.Sprintf("http://%s:%s@%s:%d", "proxyUser", "proxyPassword", "proxyServer", 8080))
show all 24 lines

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

var pn *pubnub.PubNub
config = pubnub.NewConfig()
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,
}
proxyURL, err := url.Parse(fmt.Sprintf("http://%s:%s@%s:%d", "proxyUser", "proxyPassword", "proxyServer", 8080))
show all 24 lines

Initialization

Add PubNub to your project using one of the procedures defined under How to Get It

Description

This function is used for initializing the PubNub Client API context. This function must be called before attempting to utilize any API functionality in order to establish account level credentials such as PublishKey and SubscribeKey.

Method(s)

To Initialize PubNub you can use the following method(s) in the Go V4 SDK:

pn := pubnub.NewPubNub(config)
ParameterTypeRequiredDescription
configConfigYesGoto Configuration for more details.

Basic Usage

Initialize the PubNub client API

Required UserId

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)

Returns

It returns the PubNub instance for invoking PubNub APIs like Publish(), Subscribe(), History(), HereNow(), etc.

Other Examples

Initialize a non-secure client

Required UserId

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 UserId

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 be notified of connectivity status, message and presence notifications via the listeners.

Listeners should be added 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
PNTimeoutCategoryProcessing has failed because of request time out.
PNDisconnectedCategoryThe SDK is not able to reach the PubNub Data Stream Network 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.
PNConnectedCategorySDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed).
PNAccessDeniedCategoryThe SDK will announce this error when the Access Manager does not allow the subscription to a channel or a channel group.
PNBadRequestCategoryPubNub API server was unable to parse SDK request correctly.
PNCancelledCategoryRequest was cancelled by user.
PNLoopStopCategorySubscription loop has been stopped due some reasons.
PNReconnectedCategorySubscription loop has been reconnected due some reasons.
PNAcknowledgmentCategoryPNAcknowledgmentCategory as the StatusCategory is the Acknowledgement of an operation (like Unsubscribe).
PNReconnectionAttemptsExhaustedThe SDK loop has been stopped due maximum reconnection exhausted.
PNNoStubMatchedCategory/PNUnknownCategoryPNNoStubMatchedCategory as the StatusCategory means an unknown status category event occurred.
PNRequestMessageCountExceededCategoryPNRequestMessageCountExceededCategory is fired when the MessageQueueOverflowCount limit is exceeded by the number of messages received in a single subscribe request.

UserId

These functions are used to set/get a user ID on the fly.

Method(s)

To set/get UserId you can use the following method(s) in Go V4 SDK:

config.SetUserId(UserId(string))
ParameterTypeRequiredDefaultDescription
UserIdstringYesUserId 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.

Basic Usage

Set User ID

Required UserId

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

Setter and getter for users auth key.

Method(s)

config.AuthKey = string
ParameterTypeRequiredDescription
AuthKeystringYesIf Access Manager is utilized, client will use this AuthKey in all restricted requests.
config.AuthKey

This method doesn't take any arguments.

Basic Usage

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 allows a subscriber to apply a filter to only receive messages that satisfy the conditions of the filter. The message filter is set by the subscribing client(s) but it is applied on the server side thus preventing unwanted messages (those that do not meet the conditions of the filter) 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
ParameterTypeRequiredDescription
filterExpressionstringYesPSV2 feature to Subscribe with a custom filter expression.
config.FilterExpression

This method doesn't take any arguments.

Basic Usage

Set Filter Expression

Required UserId

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