GoPubNub Go V4 SDK v4.1.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



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