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.
Prerequisites:
Now let’s get started!
Subscribe to PubNub Channel Using Javascript
Subscribe/presence/unsubscribe are implemented on the client end using the PubNub Javascript SDK. To use the SDK, we need to include the JavaScript SDK in the code:
Initialize with Publish & Subscribe Keys in Javascript. The uuid for the application is sent from the server.
Subscribe to a PubNub channel in Javascript
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.
Publish runs on the app engine. A button input type is created on the HTML page. This button is linked to a javascript function which asks the user to enter the message to publish. When entered the query is posted using jQuery to the server. This calls the publish handler on the server.
The following code is used on the server to create the publish feature.
Initialize a new PubNub instance
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:
Publish
We’ve already covered the implementation of Init in the above section “Initialize a new PubNub instance”, and handleResult in the next section below.
In the Publish method you need to give same PubNub channel name as the one subscribed (using Javascript). And the message to publish.
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: