SelectPubNub Go SDK “3.16.1”

These docs are for version “3.16.1” of the Go SDK. To check out the docs for the latest version Click Here.
 

PubNub 4.0 for Go is our latest and greatest! Please click here for our PubNub 4.0 for Go docs and SDK.

PubNub 3.x for Go will encounter End Of Life (EOL) Jun 18, 19. All users currently on 3.x should begin migrating to 4.x. The 3.x SDK will continue to work. We will no longer support it and if you run into an issue, we will request that you upgrade to the latest version before solving the issue.

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

go get github.com/pubnub/go
cd $GOPATH/src/github.com/pubnub/go
git checkout master_3x



  • Step 1: Fetch the package using go get github.com/pubnub/go
  • Step 2: Browse to `$GOPATH/src/github.com/pubnub/go` using the command cd $GOPATH/src/github.com/pubnub/go
  • Step 3: Switch the branch to `master_3x` using the command git checkout master_3x
  • Step 4: Use the package

    import (
        "github.com/pubnub/go/messaging"
    )
package main

import (
    "encoding/json"
    "fmt"
    "github.com/pubnub/go/messaging"
    "strings"
)

func main() {
    pubnub := messaging.NewPubnub("demo", "demo", "", "", false, "", nil)
    channel := "hello_world"

    connected := make(chan struct{})
    msgReceived := make(chan struct{})

    successChannel := make(chan []byte)
    errorChannel := make(chan []byte)

    go pubnub.Subscribe(channel, "", successChannel, false, errorChannel)

    go func() {
        for {
            select {
                case response := <-successChannel:
                    var msg []interface{}

                    err := json.Unmarshal(response, &msg)
                    if err != nil {
                        panic(err.Error())
                    }

                    switch t := msg[0].(type) {
                        case float64:
                            if strings.Contains(msg[1].(string), "connected") {
                                close(connected)
                            }
                        case map[string]interface{}:
                            fmt.Println(t["msg"])
                            close(msgReceived)
                        case []interface{}:
                            fmt.Println(string(response))
                            close(msgReceived)
                        default:
                            panic(fmt.Sprintf("Unknown type: %T", t))
                    }
                case err := <-errorChannel:
                    fmt.Println(string(err))
                    return
                case <-messaging.SubscribeTimeout():
                    panic("Subscribe timeout")
            }
        }
    }()

    <-connected

    publishSuccessChannel := make(chan []byte)
    publishErrorChannel := make(chan []byte)

    msg := map[string]interface{}{
        "msg":        "hello",
    }
    go pubnub.Publish(channel, msg,
            publishSuccessChannel, publishErrorChannel)

    go func() {
        select {
            case result := <-publishSuccessChannel:
                fmt.Println(string(result))
            case err := <-publishErrorChannel:
                fmt.Printf("Publish error: %s\n", err)
            case <-messaging.Timeout():
                fmt.Println("Publish timeout")
        }
    }()

    <-msgReceived
}
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 publish_key if you intend to publish from this instance, and the secretkey if you wish to perform PAM administrative operations from this Go 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.

pubnub := messaging.NewPubnub("demo", "demo", "", "", false, "", nil)
Call GetTime() to verify the client connectivity to the origin:
successChannel := make(chan []byte)
errorChannel := make(chan []byte)

go pubnub.GetTime(successChannel, errorChannel)

select {
    case msg := <-successChannel:
        time := strings.Trim(string(msg), "[]")
        fmt.Println(time)
    case err := <-errorChannel:
        fmt.Println(string(err))
    case <-messaging.Timeout():
        fmt.Println("GetTime() timeout")
}
Subscribe (listen on) a channel (it's async!):
successChannel := make(chan []byte)
errorChannel := make(chan []byte)

go pubnub.Subscribe("hello_world", "", successChannel, false, errorChannel)

for {
    select {
    case response := <-successChannel:
        var msg []interface{}

        err := json.Unmarshal(response, &msg)
        if err != nil {
            fmt.Println(err)
            return
        }

        switch m := msg[0].(type) {
        case float64:
            fmt.Println(msg[1].(string))
        case []interface{}:
            fmt.Printf("Received message '%s' on channel '%s'\n", m[0], msg[2])
            return
        default:
            panic(fmt.Sprintf("Unknown type: %T", m))
        }

    case err := <-errorChannel:
        fmt.Println(string(err))
    case <-messaging.SubscribeTimeout():
        fmt.Println("Subscribe() timeout")
    }
}
Publish a message to a channel:
successChannel := make(chan []byte)
errorChannel := make(chan []byte)
message := struct { 
    First string `json:"first"` 
    Second string `json:"second"` 
    Age int `json:"age"` 
    Region string `json:"region"` 
} { 
    "Robert", 
    "Plant", 
    59, 
    "UK", 
}
go pubnub.Publish(
    "my_channel", 
    message, 
    successChannel, 
    errorChannel
)
select
{ 
    case response := <-successChannel: 
        fmt.Println(string(response)) 
    case err := <-errorChannel: 
        fmt.Println(string(err)) 
    case <-messaging.Timeout(): 
        fmt.Println("Publish() timeout") 
}
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
successChannel := make(chan []byte)
errorChannel := make(chan []byte)

go pubnub.HereNow("my_channel", "", true, false, successChannel, errorChannel)

select {
case response := <-successChannel:
    fmt.Println(string(response))
case err := <-errorChannel:
    fmt.Println(string(err))
case <-messaging.Timeout():
    fmt.Println("HereNow() timeout")
}
Subscribe to realtime Presence events, such as join, leave, and timeout, by UUID. Adding -pnpres suffix to a channel name will subscribe to presence 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
successChannel := make(chan []byte)
errorChannel := make(chan []byte)

go pubnub.Subscribe("my_channel-pnpres", "", successChannel, true, errorChannel)

for {
    select {
    case response := <-successChannel:
        var msg []interface{}

        err := json.Unmarshal(response, &msg)
        if err != nil {
            fmt.Println(err)
            return
        }

        switch m := msg[0].(type) {
        case float64:
            fmt.Println(msg[1].(string))
        case []interface{}:
            fmt.Printf("Received message '%s' on channel '%s'\n", m[0], msg[2])
            return
        default:
            panic(fmt.Sprintf("Unknown type: %T", m))
        }

    case err := <-errorChannel:
        fmt.Println(string(err))
    case <-messaging.SubscribeTimeout():
        fmt.Println("Subscribe() timeout")
    }
}
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
successChannel := make(chan []byte)
errorChannel := make(chan []byte)

go pubnub.History("my_channel", "", 100, 0, 0, false, false, successChannel, errorChannel)

select {
	case response := <-successChannel:
		fmt.Println(string(response))
	case err := <-errorChannel:
		fmt.Println(string(err))
	case <-messaging.Timeout():
		fmt.Println("History() timeout")
}
Stop subscribing (listening) to a channel.
successChannel := make(chan []byte)
errorChannel := make(chan []byte)

go pubnub.Unsubscribe("my_channel", successChannel, errorChannel)

select {
case response := <-successChannel:
    fmt.Println(string(response))
case err := <-errorChannel:
    fmt.Println(string(err))
case <-messaging.Timeout():
    fmt.Println("Unsubscribe() timeout")
}