websocket

package
v0.0.0-...-d1dd459 Latest Latest
Warning

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

Go to latest
Published: May 22, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package websocket provides a github.com/coder/websocket binding for the runtime/websocket.Conn interface. It also provides an HTTP upgrade handler that registers new connections with a runtime/websocket.Hub.

This package contains no scheduling or broadcasting logic — that lives in runtime/websocket.

Index

Constants

View Source
const (
	// ErrAdapterWSUpgrade indicates a WebSocket upgrade failure.
	ErrAdapterWSUpgrade errcode.Code = "ERR_ADAPTER_WS_UPGRADE"
	// ErrAdapterWSWrite indicates a WebSocket write failure.
	ErrAdapterWSWrite errcode.Code = "ERR_ADAPTER_WS_WRITE"
	// ErrAdapterWSClosed indicates an operation on a closed connection.
	ErrAdapterWSClosed errcode.Code = "ERR_ADAPTER_WS_CLOSED"
)

Adapter-level error codes for the github.com/coder/websocket binding.

Variables

This section is empty.

Functions

func UpgradeHandler

func UpgradeHandler(hub *rtws.Hub, cfg UpgradeConfig) (http.Handler, error)

UpgradeHandler returns an http.Handler that upgrades HTTP connections to WebSocket and registers them with the Hub. It rejects a nil hub or an invalid cfg at construction time — error-first fail-fast — so static-wiring mistakes surface at composition root instead of the first HTTP request (PR-MODE-6.1). SEC-FAIL-CLOSED: the previous behavior of silently setting InsecureSkipVerify=true for empty origins is removed.

Types

type Conn

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

Conn wraps a github.com/coder/websocket.Conn and implements runtime/websocket.Conn.

Close is lock-free (coder/websocket.Conn.CloseNow is internally synchronized) so it can interrupt an in-flight Write immediately by closing the underlying TCP connection. Write uses mu only to serialize concurrent writes.

Instances are constructed internally by UpgradeHandler / acceptUpgradeAndRegister; external code must interact with WebSocket connections via the runtime/websocket.Conn interface that this type satisfies.

func (*Conn) Close

func (c *Conn) Close() error

Close performs an immediate transport close (CloseNow). It does NOT acquire mu, so it never blocks behind an in-flight Write. The underlying TCP close causes any concurrent Write to fail immediately.

func (*Conn) ID

func (c *Conn) ID() string

func (*Conn) Ping

func (c *Conn) Ping(ctx context.Context) error

func (*Conn) Principal

func (c *Conn) Principal() *auth.Principal

Principal returns the authenticated principal bound at handshake time. May be nil only when the adapter is misconstructed; production wiring always supplies a non-nil principal (anonymous endpoints use auth.NewAnonymousAuthenticator which returns PrincipalAnonymous).

func (*Conn) Read

func (c *Conn) Read(ctx context.Context) ([]byte, error)

func (*Conn) RemoteAddr

func (c *Conn) RemoteAddr() string

func (*Conn) Write

func (c *Conn) Write(ctx context.Context, data []byte) error

type UpgradeConfig

type UpgradeConfig struct {
	// AllowedOrigins lists the origin patterns authorized for the upgrade.
	// Each entry must be an origin pattern in the form scheme://host[:port],
	// optionally with glob wildcards (e.g. "https://example.com",
	// "https://*.example.com", "http://*", "http://localhost:*"). Bare host
	// patterns (e.g. "example.com") are rejected because coder/websocket's
	// OriginPatterns matches against the request's Origin header, which
	// always carries a scheme — a bare host would never match a real
	// browser handshake and would silently disable origin checking.
	//
	// AllowedOrigins must be non-empty and must not contain the full
	// wildcard "*". The error-returning UpgradeHandler rejects invalid
	// configuration; UpgradeHandler returns an error for invalid configuration.
	// Validate normalizes whitespace in-place so that
	// the slice handed to coder/websocket is the exact one that passed
	// validation (no trim drift between check and runtime).
	AllowedOrigins []string

	// Authenticator validates the HTTP request before WebSocket upgrade.
	// Required (nil → ErrWebsocketAuthenticatorMissing at construction).
	//
	// The Authenticator runs BEFORE websocket.Accept; rejection writes a
	// plain-text 401 directly to the response writer (browser WebSocket APIs
	// cannot read the response body, so envelope JSON is meaningless).
	//
	// Composition root selects one of:
	//   - auth.NewJWTAuthenticator(verifier)        — token-via-Authorization-header
	//   - auth.NewContextAuthenticator()            — already authenticated by listener middleware
	//   - auth.NewAnonymousAuthenticator()          — explicit unauthenticated channel
	//   - custom auth.AuthenticatorFunc             — query-param / cookie / subprotocol token
	//
	// ref: coder/websocket accept.go — http.Error(w, err.Error(), code) before Accept
	Authenticator auth.Authenticator
}

UpgradeConfig configures the WebSocket upgrade handler.

func (*UpgradeConfig) Validate

func (c *UpgradeConfig) Validate() error

Validate checks that the UpgradeConfig is well-formed and rewrites AllowedOrigins with the trimmed, validated patterns so the slice handed to coder/websocket.AcceptOptions.OriginPatterns is identical to the one that was checked. Pointer receiver is required so the rewrite is visible to the caller's local cfg copy inside UpgradeHandler.

Jump to

Keyboard shortcuts

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