Configuration API for PubNub 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
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 SDK:
config := pubnub.NewConfigWithUserId(UserId)
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
SubscribeKey | string | Yes | SubscribeKey from Admin Portal. | |
PublishKey | string | Optional | None | PublishKey from Admin Portal (only required if publishing). |
SecretKey | string | Optional | None | SecretKey (only required for modifying/revealing access permissions). |
SetUserId | UserId | Yes | 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 theuserId , you won't be able to connect to PubNub. | |
AuthKey | string | Optional | None | If Access Manager is utilized, client will use this AuthKey in all restricted requests. |
Secure | bool | Optional | True | Use SSL . |
MessageQueueOverflowCount | int | Optional | 100 | When the limit is exceeded by the number of messages received in a single subscribe request, a status event PNRequestMessageCountExceededCategory is fired. |
ConnectTimeout | int | Optional | 5 | How long to wait before giving up connection to client. The value is in seconds. |
SubscribeRequestTimeout | int | Optional | 310 | How long to keep the Subscribe loop running before disconnect.The value is in seconds. |
NonSubscribeRequestTimeout | int | Optional | 10 | On Non subscribe operations, how long to wait for server response.The value is in seconds. |
FilterExpression | string | Optional | None | Feature to subscribe with a custom filter expression. |
Origin | string | Optional | ps.pndsn.com | Custom Origin if needed. |
MaximumReconnectionRetries | int | Optional | unlimited (-1) | The config sets how many times to retry to reconnect before giving up. |
SetPresenceTimeout | int | Optional | 0 | The setting with set the custom presence server timeout.The value is in seconds. |
SetPresenceTimeoutWithCustomInterval | int | Optional | 0 | The 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. |
SuppressLeaveEvents | bool | Optional | When true the SDK doesn't send out the leave requests. | |
MaxIdleConnsPerHost | int | Optional | 30 | Used to set the value of HTTP Transport's MaxIdleConnsPerHost. |
FileMessagePublishRetryLimit | int | Optional | 5 | The number of tries made in case of Publish File Message failure. |
CryptoModule | crypto.NewAesCbcCryptor(CipherKey, UseRandomInitializationVector) crypto.NewLegacyCryptor(CipherKey, UseRandomInitializationVector) | Optional | 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 | This way of setting this parameter is deprecated, pass it to CryptoModule instead. CipherKey is passed, all communications to/from PubNub will be encrypted. | |||
UseRandomInitializationVector | true | This way of setting this parameter is deprecated, pass it to CryptoModule instead. 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 | 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
provides encrypt/decrypt functionality for messages and files. From the 7.1.2 release on, you can configure how the actual encryption/decryption algorithms work.
Each PubNub SDK is bundled with two ways of encryption: the legacy encryption with 128-bit cipher key entropy and the recommended 256 bit AES-CBC encryption. For more general information on how encryption works, refer to the Message Encryption and File Encryption sections.
If you do not explicitly set the CryptoModule
in your app and have the cipherKey
and useRandomInitializationVector
params set in PubNub config, the client defaults to using the legacy 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.
CryptoModule
configuration
To configure the CryptoModule
to encrypt all messages/files, you can use the following methods in the Go SDK:
// encrypts using 256 bit AES-CBC cipher (recommended)
// decrypts data encrypted with the legacy and the 256 bit AES-CBC ciphers
config.CryptoModule = crypto.NewAesCbcCryptoModule("cipherKey", true)
// encrypts with 128-bit cipher key entropy (legacy)
// decrypts data encrypted with the legacy and the 256 bit AES-CBC ciphers
config.CryptoModule = crypto.NewLegacyModule("cipherKey", true)
Your client can decrypt content encrypted using either of the modules. This way, you can interact with historical messages or messages sent from older clients while encoding new messages using the more secure 256 bit AES-CBC cipher.
Older SDK versions
Apps built using the SDK versions lower than 7.1.2 will not be able to decrypt data encrypted using the 256 bit AES-CBC cipher. Make sure to update your clients or encrypt data using the legacy algorithm.
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.NewConfigWithUserId(UserId("myUniqueUserId") )
// 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"
// the cryptography module used for encryption and decryption
config.CryptoModule = crypto.NewAesCbcCryptoModule("cipherKey", true)
// user ID to be used as a device identifier if you haven't set it already
show all 36 linesRest 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.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,
}
proxyURL, err := url.Parse(fmt.Sprintf("http://%s:%s@%s:%d", "proxyUser", "proxyPassword", "proxyServer", 8080))
show all 24 linesThe following sample configures a client to use a proxy for non-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.NonSubscribeRequestTimeout) * time.Second,
}
proxyURL, err := url.Parse(fmt.Sprintf("http://%s:%s@%s:%d", "proxyUser", "proxyPassword", "proxyServer", 8080))
show all 24 linesInitialization
Add PubNub to your project using one of the procedures defined in the Getting Started guide.
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 SDK:
pn := pubnub.NewPubNub(config)
Parameter | Type | Required | Description |
---|---|---|---|
config | Config | Yes | Goto 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 linesRemove 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 linesListener status events
Category | Description |
---|---|
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 | PNAcknowledgmentCategory as the StatusCategory is the Acknowledgement of an operation (like Unsubscribe). |
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. |
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 SDK:
config.SetUserId(UserId(string))
Parameter | Type | Required | Default | Description |
---|---|---|---|---|
UserId | string | Yes | 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.
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
Parameter | Type | Required | Description |
---|---|---|---|
AuthKey | string | Yes | If 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.