Building a Chat Server with Go: Make a Chat App
Are you thinking of building a chat application in Go? You’ve come to the right place! This post will walk you through everything you need to know to make a chat app with the Stream Chat API and will show a working example server that ties all the concepts discussed in this tutorial together.
The source code used for this tutorial can be found on GitHub if you'd like to take a peek at the finished product.
What Does a Chat Server Do?
For a chat server to be useful, it must be capable of performing at least the following tasks:
- Receiving messages from client applications and distributing them to other clients
- Broadcasting general notifications to all clients, such as those for when a user joins or leaves a channel
- Raising events so that a client can make the appropriate response to an event
- Managing the process of moderating users of the application
Stream Chat can do all these (and much more!), but we’ll only consider a subset of the features available in this article.
Signing Up for Stream
Before we continue, make sure to sign up for a free Stream account here and create a new application once you are signed in. You will find your application keys at the bottom of your Stream Dashboard:
Set these keys aside (and keep them safe!); we'll be using them later to authenticate our app.
Setting Up the SDK with Golang
Install the official Golang API client for Stream with the following command:
$ go get github.com/GetStream/stream-chat-go/v2
You can import it into your project as follows:
To instantiate the client object, you need to pass in the application key and secret that you retrieved from your dashboard. Ideally, you’d have them stored as environmental variables in a
.env file at the root of your project, so that they are not publicly viewable:
You can use godotenv to load the configuration variables from your
.env file, and create a new Stream client with the code below:
Creating and Updating Users
To create or update users, Stream exposes the
client.UpdateUser method. Here’s how you can use it to create a new user in your app:
By default, users are assigned the user role, but you can change it to any of the available channel roles including admin, channel_member, moderator, guest, or anonymous. You can also configure other properties such as name, image (avatar), and a map of user-related properties:
If you want to create or update multiple users at once, you can use the
client.UpdateUsers method, which expects any number of Users. The updated info will be returned as a map of Users.
Generating Authentication Tokens
Before a user is allowed to interact with your application, you need to generate a token that you’ll send back to the client-side to prove that the user was successfully authenticated.
To create a user token, you need to pass in the ID of the user, and the expiration time of the token:
The token that is returned will be a byte slice, which you can convert to a string using
Stream allows you to fetch a user, or group of users, based on some query parameters. The example below shows how you can retrieve the details for three users in one API call:
QueryUsers method expects a QueryOption argument, in which you can specify filters, which will determine what set of users will be returned. Here’s another example showing how to retrieve banned users:
You can check out this link for other query filters available to you. The
QueryOption argument also supports a
Limit property, which you can use to limit the number of results, and an
Offset property, which you can use for pagination.
Channels are an essential aspect of Stream’s Chat API. A "channel" is a single place for users to share messages, reactions, and files, and there are five types of channels available, by default, which are customized for different use cases.
The five default types of channels are:
- Livestream: Chat for services, such as Twitch
- Messaging: Configured for apps, such as WhatsApp or Facebook Messenger
- Team: Good defaults for group messaging apps, such as Slack
- Gaming: Configured for in-game chat
- Commerce: Good defaults for building a live chat service, such as Intercom
Let’s assume you are building some sort of Slack clone. You might want to create a General channel where new users are added to by default. Here’s how you can do so with Stream:
The first argument to
CreateChannel is the channel type discussed above, followed by the ID of the channel, and the ID of the user creating this channel. The final argument is the channel data, which can contain anything you want, except for the following reserved fields: name, image, and members. One thing to note here is that the extra data for the channel must not exceed 5KB in size.
Next, let’s look at a few things you can do with a channel once it has been initialized.
Adding Members to a Channel
To add users as members of a channel, use the
AddMembers method on the channel, as shown below:
Message object allows you to show a system message on the channel to indicate that something has changed. The above code will have the following effect in the application UI if you use Stream’s React components for your frontend.
Remove Members from a Channel
Removing users from a channel is as easy calling the
RemoveMembers method. It works the same way as
Updating a Channel
You can change a channel’s properties by calling the
Update method. You'll need to pass a map that contains the new channel information, as well as a message object that indicates what changed or
nil if you don’t want to show a message.
Here’s how that works:
You can also change things like the channel image and roles for its members. If you mark a channel as frozen, new messages sent to the channel will be blocked.
Moderating a Channel
You can set users as moderators for a channel. This permits them to ban any user who does not adhere to the set standards for the channel or application. To give moderation capabilities to any user, use the
If you want to produce a system message after making a user a moderator, use the
A moderator can ban a user using the
The first argument is the
userID to be banned, while the second is the
userID of the admin or moderator who is effecting the ban. You can set the reason for the ban, and a duration for how long the ban should last in the final argument to
BanUser. By default, a ban is indefinite.
To restore channel access to a banned user, use the
If you want to ban or unban a user from the chat app entirely, and not just a specific channel, use the
UnBanUser methods on the
You can read more about the moderation tools available to you here.
To send messages to a channel, you can use the
SendMessage method. It accepts a
Message object and the
userID of the sender. Here’s the simplest example of how to send a text message with Stream chat:
And here’s a more complicated example showing how you can attach an image, and mention a user in a message:
Here’s a working example that creates a new user, generates an authentication token for the user, and automatically adds them to a default "General" channel:
To test it out, paste this code into your
main.go file, and start the server using
go run main.go.
Note: Make sure that your
.envfile is configured correctly before starting the server.
POST request to the
/join endpoint using Postman, as shown below. You will receive a response with the user details, authentication token for the user, and API key if all goes well:
Building a chat server is a complex undertaking, but with Stream’s Chat service and Go, it’s much easier to get one up and running quickly. We’ve only scratched the surface of all the features available to you in this post, so be sure to check the chat docs, as well as the Go SDK docs if you want to furnish your server with additional functionality.
Thanks for reading and happy coding!