Sling Academy
Home/Golang/Implementing Typing Indicators in a Chat Application Using WebSockets in Go

Implementing Typing Indicators in a Chat Application Using WebSockets in Go

Last updated: November 26, 2024

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-app

Implementing WebSockets in Go

We'll use the popular gorilla/websocket package to handle WebSockets in Go:

$ go get -u github.com/gorilla/websocket

Start 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.

Next Article: Using WebSockets for Multiplayer Game Development in Go

Previous Article: Creating a Live Chat Support System with WebSockets in Go

Series: Websocket & Chat Programs in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant