Real-time chat applications have become a staple in many technology stacks, allowing users to communicate instantly. One feature that significantly enhances the user experience is the typing indicator. This tutorial will show how you can implement typing indicators in a chat application using WebSockets with Go.
Setting Up Your Go Environment
Before getting started, ensure that you have Go installed on your system. You can download it from the official Go website. Once installed, set up a new module in your project directory:
$ mkdir chat-app
$ cd chat-app
$ go mod init example.com/chat-appImplementing WebSockets in Go
We'll use the popular gorilla/websocket package to handle WebSockets in Go:
$ go get -u github.com/gorilla/websocketStart by creating a Go file to handle WebSocket connections:
package main
import (
"fmt"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool {
return true
},
}
func handleConnections(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Println(err)
return
}
defer ws.Close()
// For handling incoming messages such as typing events
}Integrating Typing Indicators
With the WebSocket connection established, it's time to handle typing indicators. When a user is typing, their client should send a typing event to the server:
Client-side Implementation
This implementation can vary based on the client technology. Here is a JavaScript example that sends a message when the user types:
const socket = new WebSocket('ws://localhost:8080');
const messageInput = document.getElementById('message-input');
messageInput.addEventListener('input', () => {
socket.send(JSON.stringify({ type: 'typing', user: 'User1' }));
});Server-side Handling
On the server-side, adjust your Go application to recognize and broadcast typing events:
func handleTyping(ws *websocket.Conn, message map[string]interface{}) {
if message["type"] == "typing" {
// Broadcast typing status to other users
// This is where you'd send the typing status to the relevant connected clients
fmt.Printf("User %s is typing...\n", message["user"])
}
}
func handleConnections(w http.ResponseWriter, r *http.Request) {
ws, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Println(err)
return
}
defer ws.Close()
for {
messageType, msg, err := ws.ReadMessage()
if err != nil {
fmt.Println(err)
break
}
var message map[string]interface{}
json.Unmarshal(msg, &message)
handleTyping(ws, message)
}
}Conclusion
The above examples provide a basic framework for implementing typing indicators in a chat application using WebSockets in Go. You can further extend these by establishing a more robust message-passing architecture, enhancing client-side communication, and integrating these indicators into an actual real-time application.