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:
1config := pubnub.NewConfigWithUserId(UserId)
| Parameter | Description | 
|---|---|
| SubscribeKey*Type: string Default: n/a | Subscribe key from the Admin Portal. | 
| PublishKeyType: string Default: None | Publish key from the Admin Portal (required if publishing). | 
| SecretKeyType: string Default: None | Secret key (only required for modifying or revealing access permissions). | 
| SetUserId*Type: UserId Default: n/a | userIdto use. TheUserIdobject takesStringas 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. | 
| AuthKeyType: string Default: None | If Access Manager is utilized, the client uses this AuthKeyin all restricted requests. | 
| SecureType: bool Default: True | Use SSL. | 
| MessageQueueOverflowCountType: int Default: 100 | Fires PNRequestMessageCountExceededCategorywhen a single subscribe response contains more than this many messages. | 
| ConnectTimeoutType: int Default: 10 | Maximum time to establish a connection, in seconds. | 
| SubscribeRequestTimeoutType: int Default: 310 | Subscribe request timeout, in seconds. | 
| NonSubscribeRequestTimeoutType: int Default: 10 | Non-subscribe request timeout, in seconds. | 
| FilterExpressionType: string Default: None | Feature to subscribe with a custom filter expression. | 
| OriginType: string Default: ps.pndsn.com | Custom origin if needed. To request a custom domain, contact support and follow the request process. | 
| MaximumReconnectionRetriesType: int Default: 50 | The config sets how many times to retry to reconnect before giving up. | 
| SetPresenceTimeoutType: 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. | 
| SetPresenceTimeoutWithCustomIntervalType: int Default: 0 | How often the client sends heartbeats. For shorter presence timeouts, set roughly to (SetPresenceTimeout / 2) - 1. | 
| SuppressLeaveEventsType: bool Default: n/a | When truethe SDK doesn't send out theleaverequests. | 
| MaxIdleConnsPerHostType: int Default: 30 | Used to set the value of HTTP Transport's MaxIdleConnsPerHost. | 
| FileMessagePublishRetryLimitType: int Default: 5 | The number of tries made in case of Publish File Message failure. | 
| CryptoModuleType:  crypto.NewAesCbcCryptor(CipherKey, UseRandomInitializationVector)crypto.NewLegacyCryptor(CipherKey, UseRandomInitializationVector)Default: None | The cryptography module used for encryption and decryption of messages and files. Takes the CipherKeyandUseRandomInitializationVectorparameters as arguments.For more information, refer to the CryptoModule section. | 
| CipherKeyType:  Default: | This way of setting this parameter is deprecated, pass it to CryptoModuleinstead.CipherKeyis passed, all communications to/from PubNub will be encrypted. | 
| UseRandomInitializationVectorType:  Default: true | This way of setting this parameter is deprecated, pass it to CryptoModuleinstead.truethe initialization vector (IV) is random for all requests (not just for file upload). Whenfalsethe IV is hard-coded for all requests except for file upload. | 
| UUIDType:  Default: n/a | This parameter is deprecated, use userIdinstead.UUIDto use. You should set a uniqueUUIDto 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
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.
1
Server response
Configured and ready to use client configuration instance.
Other examples
Configure request timeouts
1
Configure presence timeout
1
Configure presence timeout with custom interval
1
Enable secure connection
1
Configure reconnection policy
1
Enable SDK logging
1
Set custom origin
1
Suppress leave events
1
Configure maximum concurrent workers
1
Proxy configuration
The following sample configures a client to use a proxy for subscribe requests:
1
The following sample configures a client to use a proxy for non-subscribe requests:
1
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:
1pn := pubnub.NewPubNub(config)
| Parameter | Description | 
|---|---|
| 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.
1
Returns
Returns the PubNub instance to call APIs such as Publish(), Subscribe(), History(), and HereNow().
Other examples
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.
1
Initialize with generated UUID
1
Event listeners
You can receive connectivity status, messages, and presence notifications via listeners.
Add listeners before calling the method.
Add listeners
1
Remove listeners
1
Handling disconnects
1
Listener 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 | 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 | PNRequestMessageCountExceededCategoryis fired when theMessageQueueOverflowCountlimit 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:
1config.SetUserId(UserId(string))
| Parameter | Description | 
|---|---|
| UserId*Type: string Default: n/a | UserIdto be used as a device identifier. If you don't set theUserId, you won't be able to connect to PubNub. | 
1config.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.
1
Get user ID
1
Authentication key
Set or get the user's authentication key.
Method(s)
1config.AuthKey = string
| Parameter | Description | 
|---|---|
| AuthKey*Type: string | If Access Manager is utilized, client will use this AuthKeyin all restricted requests. | 
1config.AuthKey
This method doesn't take any arguments.
Sample code
Set auth key
1
Get auth key
1
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)
1config.FilterExpression = string
| Parameter | Description | 
|---|---|
| filterExpression*Type: string | PSV2 feature to Subscribewith a custom filter expression. | 
1config.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.
1
Get filter expression
1