GoGo V4 SDK v4.5.1

 

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 get github.com/pubnub/go
If you encounter issues with the dependencies, use the dep ensure command to fetch the dependencies.


View Supported Platforms
Add PubNub to your project using one of the procedures defined under How to Get It.
import (
    "fmt"

    pubnub "github.com/pubnub/go"
)

func main() {
    config := pubnub.NewConfig()
    config.SubscribeKey = "demo"
    config.PublishKey = "demo"

    pn := pubnub.NewPubNub(config)
    listener := pubnub.NewListener()
    doneConnect := make(chan bool)
    donePublish := make(chan bool)

    msg := map[string]interface{}{
        "msg": "hello",
    }
    go func() {
        for {
            select {
            case status := <-listener.Status:
                switch status.Category {
                case pubnub.PNDisconnectedCategory:
                    // This event happens when radio / connectivity is lost
                case pubnub.PNConnectedCategory:
                    // Connect event. You can do stuff like publish, and know you'll get it.
                    // Or just use the connected event to confirm you are subscribed for
                    // UI / internal notifications, etc
                    doneConnect <- true
                case pubnub.PNReconnectedCategory:
                    // Happens as part of our regular operation. This event happens when
                    // radio / connectivity is lost, then regained.
                }
            case message := <-listener.Message:
                // Handle new message stored in message.message
                if message.Channel != "" {
                    // Message has been received on channel group stored in
                    // message.Channel
                } else {
                    // Message has been received on channel stored in
                    // message.Subscription
                }
                if msg, ok := message.Message.(map[string]interface{}); ok {
                    fmt.Println(msg["msg"])
                }
                /*
                    log the following items with your favorite logger
                        - message.Message
                        - message.Subscription
                        - message.Timetoken
                */

                donePublish <- true
            case <-listener.Presence:
                // handle presence
            }
        }
    }()

    pn.AddListener(listener)

    pn.Subscribe().
       Channels([]string{"hello_world"}).
       Execute()

    <-doneConnect

    response, status, err := pn.Publish().
        Channel("hello_world").Message(msg).Execute()

    if err != nil {
        // Request processing failed.
        // Handle message publish error
    }

    fmt.Println(response, status, err)

    <-donePublish
}
In addition to the Hello World sample code, we also provide some copy and paste snippets of common API functions:

Instantiate a new Pubnub instance. Only the SubscribeKey is mandatory. Also include PublishKey if you intend to publish from this instance, and the SecretKey if you wish to perform PAM administrative operations from this Go V4 instance.

For security reasons you should only include the secret-key on a highly secured server. The secret-key is only required for granting rights using our Access Manager.

When you init with SecretKey, you get root permissions for the Access Manager. With this feature you don't have to grant access to your servers to access channel data. The servers get all access on all channels.

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

config := pubnub.NewConfig()
config.PublishKey = "my-pub-key"
config.SubscribeKey = "my-sub-key"

pn := pubnub.NewPubNub(config)
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 userEvent := <-listener.UserEvent:
            fmt.Println(fmt.Sprintf("userEvent.Channel: %s", userEvent.Channel))
            fmt.Println(fmt.Sprintf("userEvent.SubscribedChannel: %s", userEvent.SubscribedChannel))
            fmt.Println(fmt.Sprintf("userEvent.Event: %s", userEvent.Event))
            fmt.Println(fmt.Sprintf("userEvent.UserID: %s", userEvent.UserID))
            fmt.Println(fmt.Sprintf("userEvent.Description: %s", userEvent.Description))
            fmt.Println(fmt.Sprintf("userEvent.Timestamp: %s", userEvent.Timestamp))
            fmt.Println(fmt.Sprintf("userEvent.Name: %s", userEvent.Name))
            fmt.Println(fmt.Sprintf("userEvent.ExternalID: %s", userEvent.ExternalID))
            fmt.Println(fmt.Sprintf("userEvent.ProfileURL: %s", userEvent.ProfileURL))
            fmt.Println(fmt.Sprintf("userEvent.Email: %s", userEvent.Email))
            fmt.Println(fmt.Sprintf("userEvent.Created: %s", userEvent.Created))
            fmt.Println(fmt.Sprintf("userEvent.Updated: %s", userEvent.Updated))
            fmt.Println(fmt.Sprintf("userEvent.ETag: %s", userEvent.ETag))
            fmt.Println(fmt.Sprintf("userEvent.Custom: %v", userEvent.Custom))
        case spaceEvent := <-listener.SpaceEvent:
            fmt.Println(fmt.Sprintf("spaceEvent.Channel: %s", spaceEvent.Channel))
            fmt.Println(fmt.Sprintf("spaceEvent.SubscribedChannel: %s", spaceEvent.SubscribedChannel))
            fmt.Println(fmt.Sprintf("spaceEvent.Event: %s", spaceEvent.Event))
            fmt.Println(fmt.Sprintf("spaceEvent.SpaceID: %s", spaceEvent.SpaceID))
            fmt.Println(fmt.Sprintf("spaceEvent.Description: %s", spaceEvent.Description))
            fmt.Println(fmt.Sprintf("spaceEvent.Timestamp: %s", spaceEvent.Timestamp))
            fmt.Println(fmt.Sprintf("spaceEvent.Created: %s", spaceEvent.Created))
            fmt.Println(fmt.Sprintf("spaceEvent.Updated: %s", spaceEvent.Updated))
            fmt.Println(fmt.Sprintf("spaceEvent.ETag: %s", spaceEvent.ETag))
            fmt.Println(fmt.Sprintf("spaceEvent.Custom: %v", spaceEvent.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.SpaceID: %s", membershipEvent.SpaceID))
            fmt.Println(fmt.Sprintf("membershipEvent.UserID: %s", membershipEvent.UserID))
            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))
        }
    }
}()
listener := pubnub.NewListener()

pn.AddListener(listener)

// some time later
pn.RemoveListener(listener)
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.
PNConnectedCategorySDK subscribed with a new mix of channels (fired every time the channel / channel group mix changed).
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.
Call Time() to verify the client connectivity to the origin:
res, status, err := pn.Time().Execute()

fmt.Println(res, status, err)
pn.Subscribe().
    Channels([]string{"my-channel"}). // subscribe to channels
    Execute()
The response of the subscription is handled by Listener. Please see the Listeners section for more details.
Publish a message to a channel:
res, status, err := pn.Publish().
    Channel("ch").
    Message("hey").
    Execute()

// handle publish result
fmt.Println(res, status, err)
Get occupancy of who's here now on the channel by UUID:
Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
res, status, err := pn.HereNow().
    Channels([]string{"my-channel-1"}).
    IncludeUUIDs(true).
    Execute()

for _, v := range res.Channels {
    fmt.Println("---")
    fmt.Println("Channel: ", v.ChannelName)
    fmt.Println("Occupancy: ", v.Occupancy)
    fmt.Println("Occupants")

    for _, v := range v.Occupants {
        fmt.Println("UUID: ", v.UUID, ", state: ", v.State)
    }
}

fmt.Println(status, err)
Subscribe to realtime Presence events, such as join, leave, and timeout, by UUID. Setting the presence attribute to a callback will subscribe to presents events on my_channel:
Requires that the Presence add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
pn.Subscribe().
    Channels([]string{"my-channel"}).
    WithPresence(true).
    Execute()
The response of the subscription is handled by Listener. Please see the Listeners section for more details.
Retrieve published messages from archival storage:
Requires that the Storage and Playback add-on is enabled for your key. How do I enable add-on features for my keys? - see http://www.pubnub.com/knowledge-base/discussion/644/how-do-i-enable-add-on-features-for-my-keys
res, status, err := pn.History().
    Channel("history_channel"). // where to fetch history from
    Count(2). // how many items to fetch
    Execute()

fmt.Println(res, status, err)
pn.Unsubscribe().
    Channels([]string{"my-channel"}).
    Execute()
The response of the subscription is handled by Listener. Please see the Listeners section for more details.