This blog will walk you through the steps to create a simple real-time chat application built with Go and PubNub. The application supports multiple clients, allows you to exchange messages instantly and shows when users go online or offline.
Resources
Running the sample application
I created a simple sample available on GitHub, go ahead and clone that application:
The next step is to obtain PubNub Keys, these keys allow your application to connect to PubNub’s infrastructure and allow the application to send real-time messages as well as check who is online or offline. You can sign up to PubNub for free and get your first set of demo keys without entering a credit card.
Sign up for a free PubNub account at https://admin.pubnub.com
Create a new app in the PubNub Admin Portal
Enable Presence Events on the keyset
Copy the Publish and Subscribe keys from the app's keyset
Next, open the application in your favourite editor and make some changes:
Edit the constants in main.go
to define your PubNub keys. You don't need to change the CHAT_CHANNEL value.
Then, install dependencies:
To test the chat functionality between two clients, open two terminal windows:
Terminal 1:
Terminal 2:
Enter different usernames in each terminal and start chatting!
If you run into any issues, check out the troubleshooting steps in the project readme.
Example Session
Understanding the Sample Application
PubNub Features Used
The sample application uses the following PubNub features:
Publish/Subscribe: Core messaging functionality
Presence: Tracks when users join/leave the chat
Real-time Events: Handles incoming messages and status updates through PubNub channels
Code Walkthrough
All of the code is contained within a single file, main.go
Initialize PubNub, this connects your application to the PubNub network.
This application handles 3 different types of events from PubNub
Firstly, status events are captured to track the application lifecycle
Chat messages are received using a message listener as follows. Note that the message also specifies the username of who sent it as well as the timestamp of when it was sent:
The application also supports presence
, meaning you will be notified when the different chat participants go online or offline. This is tracked using a presence event on the channel as follows:
Finally, register the listener, subscribe to the channel, and wait for incoming connections:
Messages are sent in the main chat loop, which will read input from the command line and publish it over PubNub as follows:
Next steps
If you have any issues, or any other questions, please contact our devrel team at devrel@pubnub.com.