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()
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). |
CipherKey | string | Optional | None | If CipherKey is passed, all communications to/from PubNub will be encrypted. |
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 64 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. |
UseRandomInitializationVector | bool | Optional | true | 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 | 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.
Basic Usage
Required UserId
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 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.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 linesThe 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 linesInitialization
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)
Parameter | Type | Required | Description |
---|---|---|---|
config | Config | Yes | Goto Configuration for more details. |
Basic Usage
Initialize the PubNub client API
Required UserId
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
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
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 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. |
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 V4 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
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.
Method(s)
config.FilterExpression = string
Parameter | Type | Required | Description |
---|---|---|---|
filterExpression | string | Yes | PSV2 feature to Subscribe with a custom filter expression. |
config.FilterExpression
This method doesn't take any arguments.
Basic Usage
Set Filter Expression
Required UserId
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)