ws

package
v1.4.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 29, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package ws provides a lightweight WebSocket helper built on top of golang.org/x/net/websocket (stdlib-compatible, no CGO).

For bidirectional real-time communication between server and frontend clients. For one-way server→client streams, use pkg/sse instead.

Usage:

func chatHandler(w http.ResponseWriter, r *http.Request) {
    ws.Handle(w, r, func(conn *ws.Conn) {
        for {
            var msg ws.Message
            if err := conn.Recv(&msg); err != nil {
                return
            }
            conn.Send(ws.Message{Type: "echo", Data: msg.Data})
        }
    })
}

Index

Constants

This section is empty.

Variables

View Source
var ErrUpgradeFailed = errors.New("ws: upgrade failed")

ErrUpgradeFailed is returned when the HTTP→WebSocket upgrade fails.

Functions

func Handle

func Handle(w http.ResponseWriter, r *http.Request, fn Handler)

Handle upgrades the HTTP connection to WebSocket and calls fn. It uses the standard HTTP hijack mechanism via golang.org/x/net/websocket semantics but implemented over net/http for zero extra dependencies.

The connection is closed automatically when fn returns.

Types

type Conn

type Conn struct {
	// contains filtered or unexported fields
}

Conn wraps the underlying connection with typed send/receive helpers.

func (*Conn) Close

func (c *Conn) Close() error

Close closes the underlying connection.

func (*Conn) Recv

func (c *Conn) Recv(v any) error

Recv decodes the next JSON message from the connection into v.

func (*Conn) Send

func (c *Conn) Send(v any) error

Send encodes v as JSON and writes it to the connection. Safe for concurrent use.

type Handler

type Handler func(conn *Conn)

Handler is a function that handles a WebSocket connection.

type Message

type Message struct {
	Type string `json:"type"`
	Data any    `json:"data,omitempty"`
}

Message is the standard JSON envelope for WebSocket messages.

{ "type": "chat", "data": { ... } }

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL