GoGo V4 Configuration API Reference for Realtime Apps

 

These docs are for PubNub 4.0 for Go which is our latest and greatest! For the docs of the older versions of the SDK, please check PubNub 3.0 for Go.

If you have questions about the PubNub for Go SDK, please contact us at support@pubnub.com.

Go V4 complete API reference for building Realtime Applications on PubNub, including basic usage and sample code.

View on GoDoc
pubnub.Config instance is storage for user-provided information which describe further PubNub client behaviour. Configuration instance contain additional set of properties which allow to perform precise PubNub client configuration.
To create configuration instance you can use the following function in the Go V4 SDK:
  1. ParameterTypeRequiredDefaultsDescription
    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.
    UUIDstringYesSDK generated UUID

    UUID to use. You should set a unique UUID to identify the user or the device that connects to PubNub.

    Allowing the SDK to generate a random UUID can result in significant billing impacts, particularly on an MAU pricing plan.

    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.
    ConnectTimeoutintOptional5

    How long to wait before giving up connection to client.


    The value is in seconds.

    SubscribeRequestTimeoutintOptional310

    How long to keep the Subscribe loop running before disconnect.


    The value is in seconds.

    NonSubscribeRequestTimeoutintOptional10

    On 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.
    setPresenceTimeoutintOptional0

    The setting with set the custom presence server timeout.


    The value is in seconds.

    setPresenceTimeoutWithCustomIntervalintOptional0

    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.

    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.
    UseRandomInitializationVectorboolOptionalfalseWhen true the IV will be random for all requests and not just file upload.
    When false the IV will be hardcoded for all requests except File Upload.
 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);
Configured and ready to use client configuration instance.

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)
Add PubNub to your project using one of the procedures defined under How to Get It.
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.
To Initialize Pubnub you can use the following method(s) in the Go V4 SDK:
  1. ParameterTypeRequiredDescription
    configConfigYesGoto Configuration for more details.
 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)
It returns the Pubnub instance for invoking PubNub APIs like Publish(), Subscribe(), History(), HereNow(), etc.
  1.  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)
  2. 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:
     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.SubscribeKey = "my-sub-key"
    
    pn := pubnub.NewPubNub(config)
  3. Set a custom UUID to identify your users.
     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 = "myPublishKey"
    config.SubscribeKey = "mySubscribeKey"
    config.UUID = "myUniqueUUID"
    
    pn := pubnub.NewPubNub(config)
These functions are used to set/get a user ID on the fly.
To set/get UUID you can use the following method(s) in Go V4 SDK
  1. ParameterTypeRequiredDefaultDescription
    UUIDstringYesSDK generated UUIDUUID to be used as a device identifier, a default UUID is generated if not passed.
  2. This method doesn't take any arguments.

 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)
Setter and getter for users auth key.
  1. ParameterTypeRequiredDescription
    AuthKeystringYesIf Access Manager is utilized, client will use this AuthKey in all restricted requests.
  2. This method doesn't take any arguments.
import (
    pubnub "github.com/pubnub/go"
)

config := pubnub.NewConfig()

config.AuthKey = "my_newauthkey"
fmt.Println(config.AuthKey)
None.

Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled for your key. See this page on enabling add-on features on your keys:

http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-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/get filters you can use the following methods. To learn more about stream filtering, refer to the stream filtering tutorial.

  1. ParameterTypeRequiredDescription
    filterExpressionstringYesPSV2 feature to Subscribe with a custom filter expression.
  2. This method doesn't take any arguments.
 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)