Feedback

GoPubNub Go SDK “3.14.0”

go get github.com/pubnub/go/messaging



Install PubNub Go SDK using your package manager or just by go get github.com/pubnub/go/messaging.

  • Use the command go get github.com/pubnub/go/messaging to download and install the package.
  • Open terminal/command prompt. Browse to the directory $GOPATH/src/github.com/pubnub/go/messaging/ Run the command go install.
  • Go to eclipse and create a new go project. Enter the project name.
  • Create a new go file in the src directory of the new project. For this example choose the Command Source File under the Source File Type with Empty Main Function.
  • Click Finish

On this file.

  • Under import add the 2 lines

    import (
        // Other imports...
        "fmt"
        "github.com/pubnub/go/messaging"
    )
  • And under main add the following line

    fmt.Println("PubNub SDK for go;", messaging.VersionInfo())
  • Run the example as a go application
  • This application will print the version info of the PubNub SDK.

Similarly you can use the other functions from the API

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 []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)

    go pubnub.Publish(channel, "Hello from PubnNub Go SDK!",
            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)

go pubnub.Publish("my_channel", "Hello from the PubNub Go SDK!", 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")
}