This tutorial will show you how to create an Google App Engine web application using the PubNub Go Programming Language SDK. We will create an app to demonstrate the functionality of PubNub real-time Pub/Sub messaging using the PubNub Golang SDK. Specifically, the example will let you subscribe to a PubNub channel, then publish and receive messages on it.
This will enable you to bidirectionally send data (both unicast and broadcast) between any number of devices.
Now let’s get started!
We need to subscribe to a channel to receive all the messages sent on the channel. This is done by using the following code:
Here channel is the name of the PubNub channel which we are subscribing to. The subscribe method asks for 2 callback methods, one for receiving the messages and the other to receive the connect status.
The following code is used on the server to create the publish feature.
To use the PubNub SDK we need to instantiate its instance. The instantiation is done my calling the new method of the messaging package.
The New constructor takes the following parameters:
We’ve already covered the implementation of Init in the above section “Initialize a new PubNub instance”, and handleResult in the next section below.
The callbackChannel is called when we the message is successfully posted. The response is something like this:
The errorChannel is called when there is an error publishing the message. Like incase of a timeout when publishing the message.
This function is a utility function used in the examples below to handle the non subscribe/presence response. You would want to adapt it to your own needs. This function reads both the errorChannel and callbackChannel until we get a response on either of the go channels.
When the message is published, the same message will be displayed in the text area on the browser as we are subscribed to the channel.
Let’s run the code!
This command imports the PubNub’s Go SDK to the path <Go-Workspace-Folder>/src/pubnub/go
The complete code is available here:
And, the full code: