Sling Academy
Home/Golang/Creating a Live Chat Support System with WebSockets in Go

Creating a Live Chat Support System with WebSockets in Go

Last updated: November 26, 2024

Live chat support systems have become an integral part of customer service strategies. They allow businesses to communicate directly with their customers in real-time, providing immediate assistance. In this article, we will walk through creating a live chat support system using WebSockets in the Go programming language (often referred to as Golang).

Introduction to WebSockets

WebSockets is a communication protocol that provides full-duplex communication channels over a single TCP connection. This is especially useful for chat applications where real-time, two-way communication is required.

Setting Up Your Go Environment

Before we begin, ensure that you have Go installed on your machine. If not, you can download it from the official website and follow the installation instructions.

$ go version
# Output should confirm Go is installed, such as:
# go version go1.17.3 darwin/amd64

Creating a Simple WebSocket Server

Let's begin by setting up a simple WebSocket server using Go. We will use the Gorilla WebSocket package, which provides a robust implementation for WebSocket communication.

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

Now, create a file named main.go and add the following code:

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 {
        _, msg, err := ws.ReadMessage()
        if err != nil {
            fmt.Println(err)
            break
        }
        fmt.Printf("Received: %s\n", msg)
    }
}

func main() {
    http.HandleFunc("/ws", handleConnections)
    fmt.Println("Server started on :8080")
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        fmt.Println("Failed to start server:", err)
    }
}

Running Your WebSocket Server

Compile and run the server using:

$ go run main.go

You should see the message Server started on :8080, indicating that your server is up and running.

Testing Your WebSocket Server

To test our server, we’ll create a simple HTML client that will connect to it.

Create an index.html file with the following content:


<!DOCTYPE html>
<html>
<head>
    <title>WebSocket Chat Test</title>
</head>
<body>
    <h1>WebSocket Chat</h1>
    <input id="messageInput" type="text" placeholder="Type a message...">
    <button onclick="sendMessage()">Send</button>
    <pre id="chatLog"></pre>

    <script>
        var ws = new WebSocket('ws://localhost:8080/ws');
        ws.onmessage = function(event) {
            var messages = document.getElementById('chatLog').
            innerText += event.data + '\n';
        };

        function sendMessage() {
            var input = document.getElementById('messageInput');
            ws.send(input.value);
            input.value = '';
        }
    </script>
</body>
</html>

Open index.html in your browser. You should be able to send messages using the input field and see them displayed in the chat log.

Conclusion

In this article, we have built a simple WebSocket server and a basic client application using Go and HTML. Although this example is basic, it provides a solid foundation to build a more sophisticated live chat support system by adding features such as message broadcasting, user management, and persistent data storage.

Next Article: Implementing Typing Indicators in a Chat Application Using WebSockets in Go

Previous Article: Integrating WebSockets with Go and React for Real-Time UIs

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