WebSockets

Real-time bidirectional communication via WebSocket. Create a Hub, upgrade HTTP connections, and broadcast messages to all connected clients.

Reverb plugin (channels + Redis)

For Laravel-style named channels, JSON subscribe/unsubscribe, and multi-instance Redis Pub/Sub fan-out, use the optional Reverb plugin (nimbus plugin:install reverb). The core websocket package below is a simple broadcast-all hub.

Quick Start

import "github.com/CodeSyncr/nimbus/websocket"

hub := websocket.NewHub()
hub.SetAllowedOrigins([]string{"https://app.example.com"})
go hub.Run()

app.Router.Get("/ws", func(c *http.Context) error {
    conn, err := hub.Upgrade(c.Response, c.Request)
    if err != nil {
        return err
    }
    defer conn.Close()

    for {
        _, msg, err := conn.ReadMessage()
        if err != nil {
            break
        }
        hub.Broadcast(msg)
    }
    return nil
})

Hub API

MethodDescription
NewHub()Create a new WebSocket hub
hub.Run()Start the hub (run in a goroutine)
hub.Upgrade(w, r)Upgrade HTTP connection to WebSocket
hub.Broadcast(msg)Send message to all connected clients

Connection API

The Conn wraps gorilla/websocket and provides:

MethodDescription
conn.ReadMessage()Read a message (blocks)
conn.WriteMessage(type, data)Write a message to the client
conn.Close()Close the connection

Real-Life Example: Chat Room

hub := websocket.NewHub()
go hub.Run()

app.Router.Get("/ws/chat", func(c *http.Context) error {
    conn, err := hub.Upgrade(c.Response, c.Request)
    if err != nil {
        return err
    }
    defer conn.Close()

    // Announce join
    hub.Broadcast([]byte(`{"event":"join","user":"` + c.Query("name") + `"}`))

    for {
        _, msg, err := conn.ReadMessage()
        if err != nil {
            break
        }

        // Wrap message with sender info
        payload := fmt.Sprintf(`{"event":"message","user":"%s","text":"%s"}`,
            c.Query("name"), string(msg))
        hub.Broadcast([]byte(payload))
    }
    return nil
})

Client Side

const ws = new WebSocket('ws://localhost:3000/ws/chat?name=Alice');
ws.onmessage = (e) => {
    const data = JSON.parse(e.data);
    if (data.event === 'message') {
        appendMessage(data.user, data.text);
    }
};
ws.send('Hello everyone!');

Best Practices

  • Always run hub.Run() in a separate goroutine
  • Set hub.SetAllowedOrigins(...) for cross-origin clients; default is same-origin only
  • Handle connection errors gracefully — clients disconnect unexpectedly
  • Use JSON for message format — consistent and easy to parse
  • Combine with Presence to track who's online
  • Consider Transmit (SSE) for server-to-client only communication
  • Use Reverb when you need channel subscriptions and horizontal scaling