Sling Academy
Home/Golang/Handling WebSocket Connections in Go

Handling WebSocket Connections in Go

Last updated: November 27, 2024

WebSockets are a crucial technology for real-time Web applications, as they allow for two-way interactive communication between the user's browser and the server. The Go programming language offers robust support for WebSockets, making it a great choice for building performant applications.

Understanding WebSockets

WebSockets provide a full-duplex communication channel over a single, long-lived connection. Unlike HTTP, which is request-response based, WebSockets allow data to flow in both directions at any time, making it ideal for use-cases such as chat applications, live notifications, and real-time updates.

Setting up WebSocket in Go

Go's standard library doesn't include direct WebSocket support, but you can use the Gorilla WebSocket package, a popular third-party library. Let's see how to set up a simple WebSocket server using this package:

import (
    "fmt"
    "net/http"
    "github.com/gorilla/websocket"
)

// Define a simple upgrader object that will be used to upgrade HTTP connections to WebSocket.
var upgrader = websocket.Upgrader{
    CheckOrigin: func(r *http.Request) bool {
        return true // Modify this in production to properly check the origin
    },
}

// function to handle WebSocket connection.
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 {
        var msg string
        // Receive messages through WebSocket connection
        err := ws.ReadJSON(&msg)
        if err != nil {
            fmt.Println("Error reading message:", err)
            break
        }
        fmt.Printf("Received: %s\n", msg)

        // Send a message back to the client
        err = ws.WriteJSON("Message received")
        if err != nil {
            fmt.Println("Error writing message:", err)
            break
        }
    }
}

// Start the WebSocket server and listen for incoming connections.
func main() {
    http.HandleFunc("/ws", handleConnections)
    fmt.Println("Server started, listening on :8080")
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        fmt.Println(err)
    }
}

Testing Your WebSocket Server

You can test your WebSocket server using a simple HTML page with JavaScript as follows:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Client</title>
</head>
<body>
    <h1>WebSocket Test</h1>
    <button id="sendBtn">Send Message</button>
    <script>
        let ws = new WebSocket("ws://localhost:8080/ws");

        ws.onopen = function() {
            console.log("Connected to the server");
        };

        ws.onmessage = function(event) {
            console.log("Received from server: ", event.data);
        };

        document.getElementById("sendBtn").onclick = function() {
            ws.send("Hello Server!");
        };
    </script>
</body>
</html>

Conclusion

Handling WebSocket connections in Go with the Gorilla WebSocket package is simple and efficient. By upgrading HTTP connections to WebSockets, implementing your server's logic, and testing using a client application, you can harness the power of real-time communication effectively. Remember to implement necessary security measures in a production environment, such as input validation and origin checks.

Next Article: Working with Headers and Cookies in Go HTTP Servers

Previous Article: Making HTTP Requests with the `net/http` Package

Series: Networking and Server

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