GoGo V4 Publish & Subscribe API Reference for Realtime Apps

Go to Configuration


 

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.

The Publish() function is used to send a message to all subscribers of a channel. To publish a message you must first specify a valid PublishKey at initialization. A successfully published message is replicated across the PubNub Real-Time Network and sent simultaneously to all subscribed clients on a channel.
Messages in transit can be secured from potential eavesdroppers with SSL/TLS by setting ssl to true during initialization.
 
Publish Anytime
It is not required to be subscribed to a channel in order to publish to that channel.
Message Data:
The message argument can contain any JSON serializable data, including: Objects, Arrays, Ints and Strings. Message data should not contain special Go V4 classes or functions as these will not serialize. String content can include any single-byte or multi-byte UTF-8 character.
Message Size:
The maximum number of characters per message is 32K by default. The maximum message size is based on the final escaped character count, including the channel name. An ideal message size is under 1800 bytes which allows a message to be compressed and sent using single IP datagram (1.5KB) providing optimal network performance.
If the message you publish exceeds the configured size, you will receive the following message:
Message Too Large Error
["PUBLISHED",[0,"Message Too Large","13524237335750949"]]

For further details please check: https://support.pubnub.com/support/discussions/topics/14000006322

Message Publish Rate:
Messages can be published as fast as bandwidth conditions will allow. There is a soft limit based on max throughput since messages will be discarded if the subscriber cannot keep pace with the publisher.
For example, if 200 messages are published simultaneously before a subscriber has had a chance to receive any messages, the subscriber may not receive the first 100 messages because the message queue has a limit of only 100 messages stored in memory.
Publishing to Multiple Channels.
It is not possible to publish a message to multiple channels simultaneously. The message must be published to one channel at a time.
Publishing Messages Reliably.
There are some best practices to ensure messages are delivered when publishing to a channel:
  • Publish to any given channel in a serial manner (i.e. not concurrently).
  • Check that the return code is success (e.g. [1,"Sent","136074940..."])
  • Publish the next message only after receiving a success return code.
  • If a failure code is returned ([0,"blah","<timetoken>"]), retry the publish.
  • Avoid exceeding the in-memory queue's capacity of 100 messages. An overflow situation (aka missed messages) can occur if slow subscribers fail to keep up with the publish pace in a given period of time.
  • Throttle publish bursts in accordance with your app's latency needs e.g. Publish no faster than 5 msgs per second to any one channel.
 
Do Not JSON serialize!
It is important to note that you should not JSON serialize when sending signals/messages via PUBNUB. Why? Because the serialization is done for you automatically. Instead just pass the full object as the message payload. PubNub takes care of everything for you.
 

Single string messages are automatically sent to APNS if mobile push is enabled and devices are registered for push on that channel. So if you use encryption (cipher key in the init) and publish the message, then it will be sent to APNS if there is a device(s) registered to that channel.

This is a legacy feature and will be deprecated soon.

To Publish a message you can use the following method(s) in the Go V4 SDK:
  1. ParameterTypeRequiredDefaultDescription
    Messageinterface{}YesThe payload
    ChannelstringYesDestination of Message
    ShouldStoreboolOptionalaccount defaultStore in history
    UsePostboolOptionalfalseUse POST to Publish
    Metainterface{}OptionalnullMeta data object which can be used with the filtering ability
    DoNotReplicateboolOptionalfalseThe message stays at one data center, it is not replicated across other POPs.
    TTLintOptional
    Set a per message time to live in storage.
    1. If ShouldStore = true, and TTL = 0, the message is stored with no expiry time.
    2. If ShouldStore = true and TTL = X (X is an Integer value), the message is stored with an expiry time of X hours.
    3. If ShouldStore = false, the TTL parameter is ignored.
    4. If TTL is not specified, then expiration of the message defaults back to the expiry value for the key.
    QueryParammap[string]stringOptionalnilQueryParam accepts a map, the keys and values of the map are passed as the query string parameters of the URL called by the API.

Publish a message to a channel:

res, status, err := pn.Publish().
    Channel("my-channel").
    Message([]string{"Hello", "there"}).
    UsePost(true).
    Execute()

fmt.Println(res, status, err)
 
Before running the above publish example, either using the Debug Console, or in a separate script running in a separate terminal window, subscribe to the same channel that is being published to.
MethodTypeDescription
TimestampintAn int representation of the time token when the message was published
  1. res, status, err := pn.Publish().
        Channel("my-channel").
        Message([]string{"Hello", "there"}).
        Meta(map[string]interface{}{
            "name": "Alex",
        }).
        Execute()
  2. res, status, err := pn.Publish().
        Channel("my-channel").
        Message([]string{"Hello", "there"}).
        Meta([]string{"1a", "2b", "3c"}).
        Execute()
  3. res, status, err := pn.Publish().
        Channel("my-channel").
        Message("test").
        ShouldStore(true).
        TTL(10).
        Execute()
The fire endpoint allows the client to send a message to PubNub Functions Event Handlers. These messages will go directly to any Event Handlers registered on the channel that you fire to and will trigger their execution. The content of the fired request will be available for processing within the Event Handler. The message sent via fire() is not replicated, and so will not be received by any subscribers to the channel. The message is also not stored in history.
To Fire a message you can use the following method(s) in the Go V4 SDK:
  1. ParameterTypeRequiredDefaultDescription
    Messageinterface{}YesThe payload
    ChannelstringYesDestination of Message
    UsePostboolOptionalfalseUse POST to Publish
    Metainterface{}OptionalnullMeta data object which can be used with the filtering ability
    TTLintOptional
    Set a per message time to live in storage.
    1. If ShouldStore = true, and TTL = 0, the message is stored with no expiry time.
    2. If ShouldStore = true and TTL = X (X is an Integer value), the message is stored with an expiry time of X hours.
    3. If ShouldStore = false, the TTL parameter is ignored.
    4. If TTL is not specified, then expiration of the message defaults back to the expiry value for the key.
    QueryParammap[string]stringOptionalnilQueryParam accepts a map, the keys and values of the map are passed as the query string parameters of the URL called by the API.

Fire a message to a channel:

res, status, err := pn.Fire().
			Channel("my-channel").
			Message("test").
			Execute()
This function causes the client to create an open TCP socket to the PubNub Real-Time Network and begin listening for messages on a specified channel. To subscribe to a channel the client must send the appropriate SubscribeKey at initialization.
By default a newly subscribed client will only receive messages published to the channel after the Subscribe() call completes.
 
You can be notified of connectivity via the envelope.status. By waiting for the envelope.status to return before attempting to publish, you can avoid a potential race condition on clients that subscribe and immediately publish messages before the subscribe has completed.
Using Go V4 SDK, if a client becomes disconnected from a channel, it can automatically attempt to reconnect to that channel and retrieve any available messages that were missed during that period by setting restore to true. By default a client will attempt to reconnect after exceeding a 320 second connection timeout.
 Unsubscribing from all the channel(s) and then subscribing to a new channel Y is not the same than Subscribing to the channel Y and then unsubscribing from the previously subscribe channel(s). Unsubscribing from all the channels resets the timetoken and thus, there could be some gaps in the subscription that may lead to a message loss.
To Subscribe to a channel you can use the following method(s) in the Go V4 SDK:
  1. ParameterTypeRequiredDescription
    Channels[]stringOptionalSubscribe to channels, Either channel or channel_group is required.
    ChannelGroups[]stringOptionalSubscribe to channel_groups, Either channel or channel_group is required.
    Timetokenint64OptionalPass a timetoken.
    PresenceEnabledboolOptionalAlso subscribe to related presence information
    QueryParammap[string]stringOptionalQueryParam accepts a map, the keys and values of the map are passed as the query string parameters of the URL called by the API.
Subscribe to a channel:
pn.Subscribe().
    Channels([]string{"my-channel"}). // subscribe to channels
    Execute()
 

PNMessage is returned in the Listeners.

The Subscribe() operation returns a PNStatus which contains the following operations:
Property NameTypeDescription
Category StatusCategoryDetails of StatusCategory are here.
Error boolThis is true if an error occurred in the execution of the operation.
ErrorData errorError data of the exception (if Error is true).
StatusCode intStatus code of the execution.
Operation OperationTypeOperation type of the request.
The Subscribe() operation returns a PNMessage for messages which contains the following operations:
MethodTypeDescription
Messageinterface{}The message sent on channel.
ChannelstringThe channel on which the message was received.
SubscriptionstringThe channel group or wildcard subscription match (if exists).
Timetokenint64Timetoken for the message.
UserMetadatainterface{}User metadata.
SubscribedChannelstringCurrent subscribed channel.
PublisherstringUUID of publisher.
The Subscribe() operation returns a PNPresence for messages which contains the following operations:
MethodTypeDescription
EventstringEvents like join, leave, timeout, state-change.
UUIDstringUUID for event.
Timestampint64Timestamp for event.
OccupancyintCurrent occupancy.
SubscriptionstringMessage has been received on Channel.
Timetokenint64Timetoken of the message.
Stateinterface{}State of the UUID.
UserMetadatamap[string]interface{}User metadata.
SubscribedChannelstringCurrent subscribed channel.
ChannelstringThe channel for which the message belongs.
  1. import (
        pubnub "github.com/pubnub/go"
    )
    
    config := pubnub.NewConfig()
    // publishKey from admin panel (only required if publishing)
    config.PublishKey = "demo" // required
    // subscribeKey from admin panel
    config.SubscribeKey = "demo"
    
    pn := pubnub.NewPubNub(config)
    
    pn.Subscribe().
        Channels([]string{"my-channel"}).
        Execute()
  2. 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.
    It is possible to subscribe to more than one channel over a single TCP socket by taking advantage of Multiplexing feature. See the Multiplexing section for more info on this feature as well as the examples below using a list or an array to specify channel name.
    import (
        pubnub "github.com/pubnub/go"
    )
    
    pn.Subscribe().
        Channels([]string{"my-channel1", "my-channel2"}).
        Execute()
  3. Requires Presence add-on XRequires that the Presence 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.
    For any given channel there is an associated Presence channel. You can subscribe directly to the channel by appending -pnpres to the channel name. For example the channel named my_channel would have the presence channel named my_channel-pnpres.
    pn.Subscribe().
        Channels([]string{"my-channel"}).
        WithPresence(true).
        Execute()
    if presence.Event == "join" {
        presence.UUID // 175c2c67-b2a9-470d-8f4b-1db94f90e39e
        presence.Timestamp // 1345546797
        presence.Occupancy // 2
    }
    if presence.Event == "leave" {
        presence.UUID // 175c2c67-b2a9-470d-8f4b-1db94f90e39e
        presence.Timestamp // 1345546797
        presence.Occupancy // 2
    }
    if presence.Event == "timeout" {
        presence.UUID // 175c2c67-b2a9-470d-8f4b-1db94f90e39e
        presence.Timestamp // 1345546797
        presence.Occupancy // 2
    }
    if presence.Event == "state-change" {
        presence.Timestamp
        presence.Occupancy
    }
    if presence.Event == "interval" {
        presence.UUID // 175c2c67-b2a9-470d-8f4b-1db94f90e39e
        presence.Timestamp // 1345546797
        presence.Occupancy // 2
    }

    When a channel is in interval mode with presence_deltas pnconfig flag enabled, the interval message may also include the following fields which contain an array of changed UUIDs since the last interval message.

    • joined
    • left
    • timedout

    For example, this interval message indicates there were 2 new UUIDs that joined and 1 timed out UUID since the last interval:

    if presence.Event == "interval" {
        presence.Occupancy // # users in channel
        presence.Join // [uuid1 uuid2]
        presence.Timeout //[uuid3]
        presence.Timestamp // unix timestamp
    }

    If the full interval message is greater than 30KB (since the max publish payload is ∼32KB), none of the extra fields will be present. Instead there will be a here_now_refresh boolean field set to true. This indicates to the user that they should do a hereNow request to get the complete list of users present in the channel.

  4. Requires Stream Controller add-on XRequires that the Stream Controller add-on is enabled with Enable Wildcard Subscribe checked 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.
    Wildcard subscribes allow the client to subscribe to multiple channels using wildcard. E.g., if you subscribe to a.* you will get all messages for a.b, a.c, a.x. The wildcarded * portion refers to any portion of the channel string name after the dot (.).
     
    3 levels (2 dots) of wildcarding is supported, e.g.:
    a.*
    a.b.*
    import (
        pubnub "github.com/pubnub/go"
    )
    
    pn.Subscribe().
        Channels([]string{"foo.*"}). // subscribe to channels information
        Execute()
  5. Requires Presence add-on XRequires that the Presence 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.
    import (
        pubnub "github.com/pubnub/go"
    )
    
    config := pubnub.NewConfig()
    config.SubscribeKey = "demo"
    config.PublishKey = "demo"
    
    pn := pubnub.NewPubNub(config)
    
    listener := pubnub.NewListener()
    done := make(chan bool)
    
    go func() {
        for {
            select {
                case status := <-listener.Status:
                switch status.Category {
                    case pubnub.PNConnectedCategory:
                    res, status, err := pn.SetState().
                        Channels([]string{"ch"}).
                        State(map[string]interface{}{
                            "field_a": "cool",
                            "field_b": 21,
                    }).Execute()
                    if err != nil {
                        fmt.Println("Error: ", err)
                    }
    
                    fmt.Println(res, status)
                        done <- true
                    }
                    case <-listener.Message:
                    case <-listener.Presence:
            }
        }
    }()
    
    pn.AddListener(listener)
    
    pn.Subscribe().
            Channels([]string{"ch"}).
            Execute()
    
    <-done
    
  6. 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.
    import (
        pubnub "github.com/pubnub/go"
    )
    
    pn.Subscribe().
        Channels([]string{"ch1", "ch2"}). // subscribe to channels
        ChannelGroups([]string{"cg1", "cg2"}). // subscribe to channel groups
        Timetoken(int64(1337)). // optional, pass a timetoken
        WithPresence(true). // also subscribe to related presence information
        Execute()
  7. Requires Stream Controller and Presence add-on XRequires that both Stream Controller and Presence add-ons are 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.
    import (
        pubnub "github.com/pubnub/go"
    )
    
    pn.Subscribe().
        ChannelGroups([]string{"cg1", "cg2"}). // subscribe to channel groups
        Timetoken(int64(1337)). // optional, pass a timetoken
        WithPresence(true). // also subscribe to related presence information
        Execute()
When subscribed to a single channel, this function causes the client to issue a leave from the channel and close any open socket to the PubNub Network. For multiplexed channels, the specified channel(s) will be removed and the socket remains open until there are no more channels remaining in the list.
 Unsubscribing from all the channel(s) and then subscribing to a new channel Y is not the same than Subscribing to the channel Y and then unsubscribing from the previously subscribe channel(s). Unsubscribing from all the channels resets the timetoken and thus, there could be some gaps in the subscription that may lead to a message loss.
To Unsubscribe from a channel you can use the following method(s) in the Go V4 SDK
  1. ParameterTypeRequiredDefaultDescription
    Channels[]stringOptionalfalseUnsubscribe to channels, Either channel or channelGroup is required.
    ChannelGroups[]stringOptionalfalseUnsubscribe to channel groups, Either channel or channelGroup is required.
    QueryParammap[string]stringOptionalnilQueryParam accepts a map, the keys and values of the map are passed as the query string parameters of the URL called by the API.
Unsubscribe from a channel:
pn.Unsubscribe().
    Channels([]string{"my-channel"}).
    Execute()
The response of the subscription is handled by Listener. Please see the Listeners section for more details.
The output below demonstrates the response to a successful call:
if presence.Event == "leave" {
    presence.UUID // left-uuid
    presence.Timestamp // 1345546797
    presence.Occupancy // 2
}
  1. 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.
    import (
        pubnub "github.com/pubnub/go"
    )
    
    pn.Unsubscribe().
        Channels([]string{"my-channel", "my-channel2"}).
        Execute()
    
    if presence.Event == "leave" {
        presence.UUID // left-uuid
        presence.Timestamp // 1345546797
        presence.Occupancy // 2
    }
  2. import (
        pubnub "github.com/pubnub/go"
    )
    
    pn.Unsubscribe().
        ChannelGroups([]string{"cg1", "cg2"}).
        Execute()
    if presence.Event == "leave" {
        presence.UUID // left-uuid
        presence.Timestamp // 1345546797
        presence.Occupancy // 2
    }
Unsubscribe from all channels and all channel groups
  • UnsubscribeAll()
pn.UnsubscribeAll()
None

You can be notified of connectivity status, message and presence notifications via the listeners.

Listeners should be added before calling the method.

import (
    pubnub "github.com/pubnub/go"
)

listener := pubnub.NewListener()

go func() {
    for {
        select {
        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 <-listener.Presence:
        }
    }
}()
listener := pubnub.NewListener()

pn.AddListener(listener)

// some time later
pn.RemoveListener(listener)
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:
        }
    }
}()
CategoryDescription
PNTimeoutCategoryProcessing has failed because of request time out.
PNDisconnectedCategoryThe 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.
PNConnectedCategoryThe 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.
PNAccessDeniedCategoryThe SDK will announce this error when the PAM (PubNub Access Manager) does not allow the subscription to a channel or a channel group.
PNBadRequestCategoryPubNub API server was unable to parse SDK request correctly.
PNCancelledCategoryRequest was cancelled by user.
PNLoopStopCategorySubscription loop has been stopped due some reasons.
PNReconnectedCategorySubscription loop has been reconnected due some reasons.
PNAcknowledgmentCategoryPNAcknowledgmentCategory as the StatusCategory is the Acknowledgement of an operation (like Unsubscribe).
PNReconnectionAttemptsExhaustedThe SDK loop has been stopped due maximum reconnection exhausted.
PNNoStubMatchedCategory/PNUnknownCategoryPNNoStubMatchedCategory as the StatusCategory means an unknown status category event occurred.
PNRequestMessageCountExceededCategoryPNRequestMessageCountExceededCategory is fired when the MessageQueueOverflowCount limit is exceeded by the number of messages received in a single subscribe request.

Go to Presence