Sling Academy
Home/Golang/Working with JSON Messages Over WebSockets in Go

Working with JSON Messages Over WebSockets in Go

Last updated: November 26, 2024

WebSockets provide a powerful and fast connection between a client and a server, making real-time applications such as chat applications, live notifications, and streaming services run smoothly. In this article, we'll explore how to send and receive JSON messages over WebSockets in Go, making your real-time solutions efficient and effective.

Setting Up Your Go Environment

Before diving into WebSockets, ensure you have Go installed on your machine. You can download it from the official Go website. Initialize a new Go project using the following commands:

$ mkdir go-websocket-example
$ cd go-websocket-example
$ go mod init go-websocket-example

Installing Gorilla WebSocket Package

The Gorilla WebSocket package is a popular choice for handling WebSocket connections in Go. Install it using:

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

Creating a WebSocket Server

First, create a simple WebSocket server. The server will use the Gorilla WebSocket package to upgrade HTTP connections to WebSocket connections, handle incoming connections, and broadcast messages to connected clients.

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 {
        var msg map[string]interface{}
        err := ws.ReadJSON(&msg)
        if err != nil {
            fmt.Println("error:", err)
            break
        }
        fmt.Printf("Received message: %v\n", msg)
    }
}

func main() {
    http.HandleFunc("/ws", handleConnections)
    fmt.Println("Server started on :8080")
    err := http.ListenAndServe(":8080", nil)
    if err != nil {
        panic("ListenAndServe: " + err.Error())
    }
}

This code snippet sets up a Go server that listens for WebSocket connections on port 8080 and outputs any received JSON message.

Creating a WebSocket Client

To interact with our Go WebSocket server, let's create a simple WebSocket client using JavaScript in an HTML file.

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

<script>
    const socket = new WebSocket('ws://localhost:8080/ws');

    socket.onopen = function() {
        console.log('Connected to server');
        socket.send(JSON.stringify({
            message: "Hello, Server!",
            date: new Date()
        }));
    };

    socket.onmessage = function(event) {
        console.log('Message from server', event.data);
    };
</script>

</body>
</html>

This client sends a JSON message to the WebSocket server once the connection is established.

Conclusion

In this guide, we learned how to set up a basic WebSocket server and client, and how to work with JSON messages between them using Go. This setup provides the foundation for building robust real-time applications that require continuous and immediate data exchange.

Next Article: Designing a Multi-Room Chat Application with WebSockets in Go

Previous Article: Creating Secure WebSocket Connections with TLS 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