runner/pkg/ws

๐Ÿ“ก pkg/ws โ€“ WebSocket Abstraction Layer

The pkg/ws package provides a simple yet powerful event-driven WebSocket interface inspired by Socket.IO, built on top of Gorilla WebSocket.
It enables clean event registration (On) and message emission (Emit) with JSON messages using a typed message format.

๐Ÿ›  Usage

To use this WebSocket handler in your own HTTP route:
go
import ( "net/http" "github.com/ParthKapoor-dev/devex/runner/pkg/ws" "github.com/ParthKapoor-dev/devex/runner/pkg/pty" ) func wsHandler(w http.ResponseWriter, r *http.Request) { socket := ws.NewWSHandler() ptyManager := pty.NewPTYManager() err := socket.Init(w, r) if err != nil { log.Println(err) } socket.On("Connection", func(data any) { fmt.Println("Client connected") }) socket.On("someEvent", func(data any) { // handle event }) }

๐Ÿ“ฆ Features

  • โ€ข๐Ÿ”Œ Init: Upgrades HTTP connection to WebSocket
  • โ€ข๐Ÿง  On(event, handler): Register handlers for incoming events
  • โ€ข๐Ÿ“ค Emit(event, data): Send structured JSON messages to client
  • โ€ข๐Ÿ” Internal read/write goroutines to manage WebSocket I/O
  • โ€ข๐Ÿ”’ Thread-safe handler registration
  • โ€ข๐Ÿ”š Close(): Gracefully closes the connection

๐Ÿงฑ Design Overview

Loading diagram...
  • โ€ข
    Messages are JSON with structure:
    json
    { "event": "eventName", "data": {} }
  • โ€ข
    Uses sync.RWMutex for thread-safe access to event handlers
  • โ€ข
    Write operations are funneled through writeChan to avoid race conditions
  • โ€ข
    Event callbacks are run in separate goroutines

๐Ÿ“„ File Overview

๐Ÿ“ View Source
FunctionDescription
NewWSHandler()Create a new handler instance
Init(w, r)Upgrades connection and starts loops
On(event, handler)Register event listener
Emit(event, data)Send message to client
readLoop()Reads incoming JSON messages
writeLoop()Writes outgoing JSON messages
triggerEvent()Executes the handler for an event
Close()Closes the connection
Broadcast()Alias to Emit (extensible for multi-client)

๐Ÿ“ฆ Structs & Types

Message

The basic JSON structure exchanged over the wire.
go
type Message struct { Event string `json:"event"` Data any `json:"data,omitempty"` }

WSHandler

The main connection manager with:
  • โ€ขconn: Gorilla WebSocket connection
  • โ€ขhandlers: map of registered event callbacks
  • โ€ขwriteChan: buffered write channel
  • โ€ขdone: signals connection closure

โœ… Example: Register & Emit

go
ws := NewWSHandler() ws.On("sayHello", func(data any) { fmt.Println("Client says:", data) }) ws.Emit("serverReady", map[string]string{"msg": "Welcome!"})

๐Ÿšง Future Improvements

  • โ€ขAdd BroadcastGroup support
  • โ€ขHeartbeat/ping-pong mechanism
  • โ€ขSupport for OnTyped and JSON validation
  • โ€ขAdd retry/backoff logic

๐Ÿงญ Related Packages


๐Ÿ”— Source