recws

package module
v1.6.2 Latest Latest
Warning

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

Go to latest
Published: May 28, 2026 License: MIT Imports: 10 Imported by: 0

README

logo

recws

Reconnecting WebSocket is a websocket client based on gorilla/websocket that will automatically reconnect if the connection is dropped - thread safe!

GoDoc Go Report Card GitHub license

Features

  • Automatic reconnection with configurable backoff
  • Thread-safe operations
  • Structured logging with configurable levels
  • Robust keepalive mechanism
  • Proper connection establishment with channel-based synchronization
  • TLS support
  • Proxy support
  • Compression support (RFC 7692)
  • Graceful shutdown support

Installation

go get github.com/inference-sh/recws

Quick Start

import "github.com/inference-sh/recws"

// Create a new reconnecting websocket
ws := &recws.RecConn{
    KeepAliveTimeout: 30 * time.Second,
}

// Connect (blocks until connection is established or timeout reached)
ws.Dial("ws://example.com/ws", nil)

// Send/receive messages
ws.WriteMessage(websocket.TextMessage, []byte("hello"))

Examples

See the examples directory for complete working examples.

Important Note

This library is designed to be used as a WebSocket client (the connecting end) that initiates connections to a WebSocket server. It is not meant to be used for implementing WebSocket server endpoints. If you're looking to implement a WebSocket server, please use the gorilla/websocket package directly instead.

Examples

See the examples directory for complete working examples.

Important Note

This library is designed to be used as a WebSocket client (the connecting end) that initiates connections to a WebSocket server. It is not meant to be used for implementing WebSocket server endpoints. If you're looking to implement a WebSocket server, please use the gorilla/websocket package directly instead.

Logo Credits

License

recws is open-source software licensed under the MIT license.

Documentation

Overview

Package recws provides websocket client based on gorilla/websocket that will automatically reconnect if the connection is dropped.

Index

Constants

This section is empty.

Variables

View Source
var ErrNotConnected = errors.New("websocket: not connected")

ErrNotConnected is returned when the application read/writes a message and the connection is closed

Functions

This section is empty.

Types

type Logger added in v1.6.0

type Logger interface {
	Debug(msg string, args ...any)
	Info(msg string, args ...any)
	Warn(msg string, args ...any)
	Error(msg string, args ...any)
}

Logger is the interface for logging operations

func DefaultLogger added in v1.6.0

func DefaultLogger() Logger

DefaultLogger returns a slog-based default logger

type RecConn

type RecConn struct {
	// RecIntvlMin specifies the initial reconnecting interval,
	// default to 2 seconds
	RecIntvlMin time.Duration
	// RecIntvlMax specifies the maximum reconnecting interval,
	// default to 30 seconds
	RecIntvlMax time.Duration
	// RecIntvlFactor specifies the rate of increase of the reconnection
	// interval, default to 1.5
	RecIntvlFactor float64
	// HandshakeTimeout specifies the duration for the handshake to complete,
	// default to 2 seconds
	HandshakeTimeout time.Duration
	// Proxy specifies the proxy function for the dialer
	// defaults to ProxyFromEnvironment
	Proxy func(*http.Request) (*url.URL, error)
	// Client TLS config to use on reconnect
	TLSClientConfig *tls.Config
	// SubscribeHandler fires after the connection successfully establish.
	SubscribeHandler func() error
	// KeepAliveTimeout is an interval for sending ping/pong messages
	// disabled if 0
	KeepAliveTimeout time.Duration
	// Compression enables per-message compression as defined in https://datatracker.ietf.org/doc/html/rfc7692
	Compression bool
	// Logger is the logger instance to use. If nil, DefaultLogger() will be used.
	Logger Logger

	*websocket.Conn
	// contains filtered or unexported fields
}

The RecConn type represents a Reconnecting WebSocket connection.

func (*RecConn) Close

func (rc *RecConn) Close()

Close closes the underlying network connection without sending or waiting for a close frame.

func (*RecConn) CloseAndReconnect

func (rc *RecConn) CloseAndReconnect()

CloseAndReconnect will try to reconnect. Safe to call concurrently — only the first caller triggers a reconnect, subsequent calls are no-ops until the reconnect completes.

func (*RecConn) Dial

func (rc *RecConn) Dial(urlStr string, reqHeader http.Header)

Dial creates a new client connection

func (*RecConn) GetDialError

func (rc *RecConn) GetDialError() error

GetDialError returns the last dialer error. nil on successful connection.

func (*RecConn) GetHTTPResponse

func (rc *RecConn) GetHTTPResponse() *http.Response

GetHTTPResponse returns the http response from the handshake. Useful when WebSocket handshake fails, so that callers can handle redirects, authentication, etc.

func (*RecConn) GetURL

func (rc *RecConn) GetURL() string

GetURL returns current connection url

func (*RecConn) IsConnected

func (rc *RecConn) IsConnected() bool

IsConnected returns the WebSocket connection state

func (*RecConn) ReadJSON

func (rc *RecConn) ReadJSON(v interface{}) error

ReadJSON reads the next JSON-encoded message from the connection.

func (*RecConn) ReadMessage

func (rc *RecConn) ReadMessage() (messageType int, message []byte, err error)

ReadMessage is a helper method for getting a reader using NextReader and reading from that reader to a buffer.

If the connection is closed ErrNotConnected is returned

func (*RecConn) SetTLSClientConfig

func (rc *RecConn) SetTLSClientConfig(tlsClientConfig *tls.Config)

func (*RecConn) Shutdown

func (rc *RecConn) Shutdown(writeWait time.Duration)

Shutdown gracefully closes the connection by sending the websocket.CloseMessage. The writeWait param defines the duration before the deadline of the write operation is hit.

func (*RecConn) WriteJSON

func (rc *RecConn) WriteJSON(v interface{}) error

WriteJSON writes the JSON encoding of v to the connection.

func (*RecConn) WriteMessage

func (rc *RecConn) WriteMessage(messageType int, data []byte) error

WriteMessage is a helper method for getting a writer using NextWriter, writing the message and closing the writer.

If the connection is closed ErrNotConnected is returned

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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