Advanced

WebSockets

Real-time updates with sessions, rooms, and HTMX integration.

HAMR's pkg/websocket package gives you a session-aware WebSocket hub with rooms, broadcasts, and HTMX integration. It's built on the coder/websocket library and works seamlessly with HTMX's hx-ext="ws" extension.

Creating the hub

cmd/site/main.go
import "github.com/FyrmForge/hamr/pkg/websocket"

hub := websocket.NewHub(websocket.WithLogger(log))
defer hub.Close()

Registering the route

internal/web/server.go
e.GET("/ws", deps.Hub.Handler())

Broadcasting messages

handler.go
// Broadcast to all connected clients.
h.hub.Broadcast([]byte("New book added!"))

// Send to a specific room.
h.hub.SendToRoom("book-42", []byte("..."))

// Send to a specific user (by subject ID).
h.hub.SendToSubject(userID, []byte("..."))

HTMX integration

With HTMX's WebSocket extension, the server can push HTML fragments that swap into the page automatically:

template
<div hx-ext="ws" ws-connect="/ws">
    <ul id="book-list">
        <!-- Server pushes <li> elements here via the hub. -->
    </ul>
</div>
Auto-reconnect
HAMR projects ship with a small ws.js helper that uses exponential backoff to reconnect dropped WebSocket sessions. Network blips don't break your real-time UI.