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. |
Get Code:
dep ensure
command to fetch the dependencies.Get Code: Source
Hello World
Add PubNub to your project using one of the procedures defined under How to Get It.Example
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 }
Copy and paste examples
Init
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 |
Initializing the client
import ( pubnub "github.com/pubnub/go" ) config := pubnub.NewConfig() config.PublishKey = "my-pub-key" config.SubscribeKey = "my-sub-key" pn := pubnub.NewPubNub(config)
Listeners
Adding Listeners
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: } } }()
Removing Listeners
listener := pubnub.NewListener() pn.AddListener(listener) // some time later pn.RemoveListener(listener)
listeners status events
Category | Description |
---|---|
PNTimeoutCategory | Processing has failed because of request time out. |
PNDisconnectedCategory | The 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. |
PNConnectedCategory | The 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. |
PNAccessDeniedCategory | The SDK will announce this error when the PAM (PubNub Access Manager) does not allow the subscription to a channel or a channel group. |
PNBadRequestCategory | PubNub API server was unable to parse SDK request correctly. |
PNCancelledCategory | Request was cancelled by user. |
PNLoopStopCategory | Subscription loop has been stopped due some reasons. |
PNReconnectedCategory | Subscription loop has been reconnected due some reasons. |
PNAcknowledgmentCategory | PNAcknowledgmentCategory as the StatusCategory is the Acknowledgement of an operation (like Unsubscribe). |
PNReconnectionAttemptsExhausted | The SDK loop has been stopped due maximum reconnection exhausted. |
PNNoStubMatchedCategory/PNUnknownCategory | PNNoStubMatchedCategory as the StatusCategory means an unknown status category event occurred. |
PNRequestMessageCountExceededCategory | PNRequestMessageCountExceededCategory is fired when the MessageQueueOverflowCount limit is exceeded by the number of messages received in a single subscribe request. |
Time
Time()
to verify the client connectivity to the origin:res, status, err := pn.Time().Execute() fmt.Println(res, status, err)
Subscribe
Subscribe (listen on) a channel
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
res, status, err := pn.Publish(). Channel("ch"). Message("hey"). Execute() // handle publish result fmt.Println(res, status, err)
Here Now
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)
Presence
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. |
History
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)
Unsubscribe
Stop subscribing (listening) to 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. |