5 Home
Virgil edited this page 2026-02-19 16:55:26 +00:00

go-ws

WebSocket hub for real-time streaming in Go.

Module forge.lthn.ai/core/go-ws
Dependency github.com/gorilla/websocket
Licence EUPL-1.2

Install

go get forge.lthn.ai/core/go-ws@latest

Quick Start

package main

import (
	"context"
	"net/http"

	ws "forge.lthn.ai/core/go-ws"
)

func main() {
	hub := ws.NewHub()

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	go hub.Run(ctx)

	http.HandleFunc("/ws", hub.Handler())
	http.ListenAndServe(":8080", nil)
}

Connect from JavaScript:

const socket = new WebSocket("ws://localhost:8080/ws");

socket.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  console.log(msg.type, msg.data);
};

// Subscribe to a process channel
socket.send(JSON.stringify({
  type: "subscribe",
  data: "process:build-1"
}));

Key Features

  • Hub pattern -- single goroutine manages all connections and channel routing
  • Channel subscriptions -- clients subscribe to named channels; messages are delivered only to subscribers
  • Process streaming -- dedicated helpers for streaming process output and status over WebSocket
  • Broadcast -- send a message to every connected client
  • Keep-alive -- automatic ping/pong with configurable read deadlines
  • Graceful shutdown -- context cancellation closes all connections cleanly
  • Concurrency-safe -- all public methods are safe for concurrent use

API Overview

Method Purpose
NewHub() Create a new hub instance
Hub.Run(ctx) Start the hub event loop (blocks until context cancels)
Hub.Handler() Return an http.HandlerFunc for WebSocket upgrades
Hub.HandleWebSocket(w, r) Directly handle a WebSocket upgrade request
Hub.Broadcast(msg) Send a message to all connected clients
Hub.SendToChannel(ch, msg) Send a message to subscribers of a channel
Hub.SendProcessOutput(id, line) Stream a line of process output
Hub.SendProcessStatus(id, status, code) Send a process status change
Hub.SendError(errMsg) Broadcast an error to all clients
Hub.SendEvent(eventType, data) Broadcast a generic event
Hub.Subscribe(client, channel) Add a client to a channel
Hub.Unsubscribe(client, channel) Remove a client from a channel
Hub.ClientCount() Number of connected clients
Hub.ChannelCount() Number of active channels
Hub.ChannelSubscriberCount(ch) Subscribers in a given channel
Hub.Stats() Return HubStats (clients + channels)

Wiki Pages