Go V4 Configuration API Reference for Realtime Apps
Go V4 complete API reference for building Realtime Applications on PubNub, including basic usage and sample code. View on GoDoc
Configuration
Description
pubnub.Config
instance is storage for user-provided information which describe further PubNub client behavior. Configuration instance contain additional set of properties which allow to perform 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 Defaults 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.UUID
string Yes SDK generated UUID UUID
to use. You should set a uniqueUUID
to identify the user or the device that connects to PubNub.
Allowing the SDK to generate a randomUUID
can result in significant billing impacts, particularly on an MAU pricing plan.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 theleave
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 false
When true
theIV
will be random for all requests and not just file upload. Whenfalse
theIV
will be hardcoded for all requests except File Upload.
Basic Usage
Note
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID
can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
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"
// UUID to be used as a device identifier, a default UUID is generated
// if not passed
config.UUID = "customUUID"
// use SSL.
config.Secure = true
// how long to wait before giving up connection to client
config.ConnectTimeout = 100
// how long to keep the subscribe loop running before disconnect
config.SubscribeRequestTimeout = 310
// on non subscribe operations, how long to wait for server response
config.NonSubscribeRequestTimeout = 300
// PSV2 feature to subscribe with a custom filter expression
config.FilterExpression = "such=wow"
// heartbeat notifications, by default, the SDK will alert on failed heartbeats.
// other options such as all heartbeats or no heartbeats are supported.
config.SetPresenceTimeoutWithCustomInterval(120,59);
config.SetPresenceTimeout(120);
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))
if err == nil {
transport.Proxy = http.ProxyURL(proxyURL)
} else {
fmt.Printf("ERROR: creatSubHTTPClient: Proxy connection error: %s", err.Error())
}
c := pn.GetSubscribeClient()
c.Transport = transport
pn.SetSubscribeClient(c)
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))
if err == nil {
transport.Proxy = http.ProxyURL(proxyURL)
} else {
fmt.Printf("ERROR: createNonSubHTTPClient: Proxy connection error: %s", err.Error())
}
c := pn.GetClient()
c.Transport = transport
pn.SetClient(c)
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)
Parameter Type Required Description config
Config Yes Goto Configuration for more details.
Basic Usage
Initialize the PubNub client API:
Note
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID
can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
import (
pubnub "github.com/pubnub/go"
)
config := pubnub.NewConfig()
config.PublishKey = "my-pub-key"
config.SubscribeKey = "my-sub-key"
config.UUID = "myUniqueUUID"
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:
Note
Always set the
UUID
to uniquely identify the user or device that connects to PubNub. ThisUUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting theUUID
can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.import ( pubnub "github.com/pubnub/go" ) config := pubnub.NewConfig() config.PublishKey = "my-pub-key" config.SubscribeKey = "my-sub-key" config.UUID = "myUniqueUUID" 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:Note
Always set the
UUID
to uniquely identify the user or device that connects to PubNub. ThisUUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting theUUID
can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.import ( pubnub "github.com/pubnub/go" ) config := pubnub.NewConfig() config.SubscribeKey = "my-sub-key" pn := pubnub.NewPubNub(config)
-
Set a custom
UUID
to identify your users.Note
Always set the
UUID
to uniquely identify the user or device that connects to PubNub. ThisUUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting theUUID
can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.import ( pubnub "github.com/pubnub/go" ) config := pubnub.NewConfig() config.PublishKey = "myPublishKey" config.SubscribeKey = "mySubscribeKey" config.UUID = "myUniqueUUID" pn := pubnub.NewPubNub(config)
Event Listeners
Description
You can be notified of connectivity status, message and presence notifications via the listeners.
Listeners should be added before calling the method.
Adding 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
fmt.Println(signal.Message)
//Publisher ID
fmt.Println(signal.Publisher)
//Timetoken
fmt.Println(signal.Timetoken)
case status := <-listener.Status:
switch status.Category {
case pubnub.PNDisconnectedCategory:
// this is the expected category for an unsubscribe. This means there
// was no error in unsubscribing from everything
case pubnub.PNConnectedCategory:
// this is expected for a subscribe, this means there is no error or issue whatsoever
case pubnub.PNReconnectedCategory:
// this usually occurs if subscribe temporarily fails but reconnects. This means
// there was an error but there is no longer any issue
case pubnub.PNAccessDeniedCategory:
// this means that PAM does allow this client to subscribe to this
// channel and channel group configuration. This is another explicit error
}
case message := <-listener.Message:
//Channel
fmt.Println(message.Channel)
//Subscription
fmt.Println(message.Subscription)
//Payload
fmt.Println(message.Message)
//Publisher ID
fmt.Println(message.Publisher)
//Timetoken
fmt.Println(message.Timetoken)
case presence := <-listener.Presence:
fmt.Println(presence.Event)
//Channel
fmt.Println(presence.Channel)
//Subscription
fmt.Println(presence.Subscription)
//Timetoken
fmt.Println(presence.Timetoken)
//Occupancy
fmt.Println(presence.Occupancy)
case uuidEvent := <-listener.UUIDEvent:
fmt.Println(fmt.Sprintf("uuidEvent.Channel: %s", uuidEvent.Channel))
fmt.Println(fmt.Sprintf("uuidEvent.SubscribedChannel: %s", uuidEvent.SubscribedChannel))
fmt.Println(fmt.Sprintf("uuidEvent.Event: %s", uuidEvent.Event))
fmt.Println(fmt.Sprintf("uuidEvent.UUID: %s", uuidEvent.UUID))
fmt.Println(fmt.Sprintf("uuidEvent.Description: %s", uuidEvent.Description))
fmt.Println(fmt.Sprintf("uuidEvent.Timestamp: %s", uuidEvent.Timestamp))
fmt.Println(fmt.Sprintf("uuidEvent.Name: %s", uuidEvent.Name))
fmt.Println(fmt.Sprintf("uuidEvent.ExternalID: %s", uuidEvent.ExternalID))
fmt.Println(fmt.Sprintf("uuidEvent.ProfileURL: %s", uuidEvent.ProfileURL))
fmt.Println(fmt.Sprintf("uuidEvent.Email: %s", uuidEvent.Email))
fmt.Println(fmt.Sprintf("uuidEvent.Updated: %s", uuidEvent.Updated))
fmt.Println(fmt.Sprintf("uuidEvent.ETag: %s", uuidEvent.ETag))
fmt.Println(fmt.Sprintf("uuidEvent.Custom: %v", uuidEvent.Custom))
case channelEvent := <-listener.ChannelEvent:
fmt.Println(fmt.Sprintf("channelEvent.Channel: %s", channelEvent.Channel))
fmt.Println(fmt.Sprintf("channelEvent.SubscribedChannel: %s", channelEvent.SubscribedChannel))
fmt.Println(fmt.Sprintf("channelEvent.Event: %s", channelEvent.Event))
fmt.Println(fmt.Sprintf("channelEvent.Channel: %s", channelEvent.Channel))
fmt.Println(fmt.Sprintf("channelEvent.Description: %s", channelEvent.Description))
fmt.Println(fmt.Sprintf("channelEvent.Timestamp: %s", channelEvent.Timestamp))
fmt.Println(fmt.Sprintf("channelEvent.Updated: %s", channelEvent.Updated))
fmt.Println(fmt.Sprintf("channelEvent.ETag: %s", channelEvent.ETag))
fmt.Println(fmt.Sprintf("channelEvent.Custom: %v", channelEvent.Custom))
case membershipEvent := <-listener.MembershipEvent:
fmt.Println(fmt.Sprintf("membershipEvent.Channel: %s", membershipEvent.Channel))
fmt.Println(fmt.Sprintf("membershipEvent.SubscribedChannel: %s", membershipEvent.SubscribedChannel))
fmt.Println(fmt.Sprintf("membershipEvent.Event: %s", membershipEvent.Event))
fmt.Println(fmt.Sprintf("membershipEvent.Channel: %s", membershipEvent.Channel))
fmt.Println(fmt.Sprintf("membershipEvent.UUID: %s", membershipEvent.UUID))
fmt.Println(fmt.Sprintf("membershipEvent.Description: %s", membershipEvent.Description))
fmt.Println(fmt.Sprintf("membershipEvent.Timestamp: %s", membershipEvent.Timestamp))
fmt.Println(fmt.Sprintf("membershipEvent.Custom: %v", membershipEvent.Custom))
case messageActionsEvent := <-listener.MessageActionsEvent:
fmt.Println(fmt.Sprintf("messageActionsEvent.Channel: %s", messageActionsEvent.Channel))
fmt.Println(fmt.Sprintf("messageActionsEvent.SubscribedChannel: %s", messageActionsEvent.SubscribedChannel))
fmt.Println(fmt.Sprintf("messageActionsEvent.Event: %s", messageActionsEvent.Event))
fmt.Println(fmt.Sprintf("messageActionsEvent.Data.ActionType: %s", messageActionsEvent.Data.ActionType))
fmt.Println(fmt.Sprintf("messageActionsEvent.Data.ActionValue: %s", messageActionsEvent.Data.ActionValue))
fmt.Println(fmt.Sprintf("messageActionsEvent.Data.ActionTimetoken: %s", messageActionsEvent.Data.ActionTimetoken))
fmt.Println(fmt.Sprintf("messageActionsEvent.Data.MessageTimetoken: %s", messageActionsEvent.Data.MessageTimetoken))
case file := <-listener.File:
fmt.Println(fmt.Sprintf("file.File.PNMessage.Text: %s", file.File.PNMessage.Text))
fmt.Println(fmt.Sprintf("file.File.PNFile.Name: %s", file.File.PNFile.Name))
fmt.Println(fmt.Sprintf("file.File.PNFile.ID: %s", file.File.PNFile.ID))
fmt.Println(fmt.Sprintf("file.File.PNFile.URL: %s", file.File.PNFile.URL))
fmt.Println(fmt.Sprintf("file.Channel: %s", file.Channel))
fmt.Println(fmt.Sprintf("file.Timetoken: %d", file.Timetoken))
fmt.Println(fmt.Sprintf("file.SubscribedChannel: %s", file.SubscribedChannel))
fmt.Println(fmt.Sprintf("file.Publisher: %s", file.Publisher))
}
}
}()
Removing 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:
}
}
}()
Listener 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 PAM (PubNub 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. |
UUID
Description
These functions are used to set/get a user ID on the fly.
Method(s)
To set/get UUID
you can use the following method(s) in Go V4 SDK:
config.UUID = string
Parameter Type Required Default Description UUID
string Yes SDK generated UUID
UUID
to be used as a device identifier, a defaultUUID
is generated if not passed.-
This method doesn't take any arguments.
Basic Usage
Note
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID
can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
import (
pubnub "github.com/pubnub/go"
)
config := pubnub.NewConfig()
config.UUID = "myUniqueUUID"
import (
pubnub "github.com/pubnub/go"
)
config := pubnub.NewConfig()
fmt.Println(config.UUID)
Authentication Key
Description
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
import (
pubnub "github.com/pubnub/go"
)
config := pubnub.NewConfig()
config.AuthKey = "my_newauthkey"
fmt.Println(config.AuthKey)
Returns
None.
Filter Expression
Requires Stream Controller add-onRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:
https://support.pubnub.com/hc/en-us/articles/360051974791-How-do-I-enable-add-on-features-for-my-keys-
Description
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/get 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
Note
Always set the UUID
to uniquely identify the user or device that connects to PubNub. This UUID
should be persisted, and should remain unchanged for the lifetime of the user or the device. Not setting the UUID
can significantly impact your billing if your account uses the Monthly Active Users (MAUs) based pricing model, and can also lead to unexpected behavior if you have Presence enabled.
import (
pubnub "github.com/pubnub/go"
)
config := pubnub.NewConfig()
config.FilterExpression = "such=wow"
fmt.Println(config.FilterExpression)