๐ก 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:
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
- โข
Messages are JSON with structure:
{
"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
Function | Description |
---|
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.
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
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
- โข๐
pkg/pty
โ Manages terminal sessions
- โข๐
pkg/fs
โ Manages filesystem read/write operations
- โข๐
runner/services/repl
โ API integration using this handler
๐ Source