websockit

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jun 16, 2022 License: MIT Imports: 9 Imported by: 0

README

websockit

GoDoc Go Report Card

Golang gorilla/websocket wrapper that provides customizable client and server implementations, read and write helpers, close and error handlers, and more

Installation

go get github.com/lossdev/websockit

Documentation

On pkg.go.dev

Examples

An echo server and client example are provided in the cmd directory

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrPingNotEnabled = errors.New("ping functionality has not been enabled yet; make a call to *WebsocketClient.EnableServerPings() before *WebsocketClient.ServerPingLoop()")

ErrPingNotEnabled is returned when a client attempts to enter a ping loop without initializing the ping options

Functions

This section is empty.

Types

type ClientPingOption

type ClientPingOption func(*pingOpts)

ClientPingOption specifies any custom options for the client ping behavior

func PingWithPongLog

func PingWithPongLog(logPongs bool) ClientPingOption

PingWithPongLog enables client logs when pong messages are received from the server end of the Websocket connection

func PingWithPongTimeout

func PingWithPongTimeout(pongTimeout time.Duration) ClientPingOption

PingWithPongTimeout sets a maximum pongTimeout allowed before the Websocket read exits with a read failure

type Websocket

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

Websocket is the embedded struct that websocket clients and servers have in common

func NewWebsocket

func NewWebsocket() *Websocket

NewWebsocket should be called for any new websocket pair, server or client. This will initialize the websocket struct values which will be used to accept any websocket options that are set

func (*Websocket) ClientSocket

func (w *Websocket) ClientSocket(connectUrl string, headers http.Header, opts ...WebsocketClientOption) (*WebsocketClient, error)

ClientSocket sets up a new client websocket end

Example
package main

import (
	"log"
	"net/http"
	"time"

	"github.com/lossdev/websockit"
)

func main() {
	ws := websockit.NewWebsocket()
	opts := []websockit.WebsocketClientOption{
		websockit.ClientWithHandshakeTimeout(5 * time.Second),
		websockit.ClientWithProxy(http.ProxyFromEnvironment),
	}
	if _, err := ws.ClientSocket("wss://ws.postman-echo.com/raw", nil, opts...); err != nil {
		log.Println(err)
	}
}
Output:

func (*Websocket) CloseNice

func (w *Websocket) CloseNice()

CloseNice closes the Websocket connection by sending a CloseNormalClosure control message to the other end of the connection

func (*Websocket) CloseNow

func (w *Websocket) CloseNow() error

CloseNow closes the Websocket connection without sending a Close control message

func (*Websocket) LocalAddr

func (w *Websocket) LocalAddr() net.Addr

LocalAddr returns the local network address

func (*Websocket) ReadLoop

func (w *Websocket) ReadLoop(readChannel chan []byte) error

ReadLoop infinitely loops, reading the current Websocket for incoming messages and inserting them into `readChannel`. If an error is returned, the client application should discard the current Websocket connection, as any new writes will be discarded, and new reads will return the same error. Because this function is blocking, it is recommended to wrap it into a goroutine

Example
package main

import (
	"log"

	"github.com/lossdev/websockit"
)

func main() {
	// you should have a *websockit.WebsocketServer / *websockit.WebsocketClient already initialized
	var ws websockit.WebsocketClient

	readChan := make(chan []byte)
	go func() {
		if err := ws.ReadLoop(readChan); err != nil {
			log.Println(err)
		}
	}()

	for msg := range readChan {
		log.Printf("read: %s\n", string(msg))
	}
}
Output:

func (*Websocket) RemoteAddr

func (w *Websocket) RemoteAddr() net.Addr

RemoteAddr returns the remote network address

func (*Websocket) ServerSocket

func (w *Websocket) ServerSocket(wr http.ResponseWriter, req *http.Request, headers http.Header, opts ...WebsocketServerOption) (*WebsocketServer, error)

ServerSocket sets up a new server websocket end

Example
package main

import (
	"log"
	"net/http"
	"time"

	"github.com/lossdev/websockit"
)

func main() {
	// this code should be placed in an HTTP handler function
	// i.e func foo(w http.ResponseWriter, r *http.Request) { ... }
	ws := websockit.NewWebsocket()
	opts := []websockit.WebsocketServerOption{
		websockit.ServerWithHandshakeTimeout(5 * time.Second),
	}

	// this is just so the snippet compiles - you'd already have `w` and `req` in scope and defined here
	var w http.ResponseWriter
	var req *http.Request

	if _, err := ws.ServerSocket(w, req, nil, opts...); err != nil {
		log.Println(err)
	}
}
Output:

func (*Websocket) WriteBinaryMessage

func (w *Websocket) WriteBinaryMessage(data []byte) error

WriteBinaryMessage writes a binary data message to the Websocket

func (*Websocket) WriteTextMessage

func (w *Websocket) WriteTextMessage(data []byte) error

WriteTextMessage writes a UTF-8 encoded interpreted message to the Websocket

type WebsocketClient

type WebsocketClient struct {
	*Websocket
	// contains filtered or unexported fields
}

WebsocketClient inherits the Websocket fields and methods, and implements its own unique methods

func (*WebsocketClient) EnableServerPings

func (w *WebsocketClient) EnableServerPings(opts ...ClientPingOption)

EnableServerPings initializes the variables controlling the options needed to enter the ping loop, and should be called before ServerPingLoop

func (*WebsocketClient) ServerPingLoop

func (w *WebsocketClient) ServerPingLoop() error

ServerPingLoop infinitely loops, sending new ping messages at a fractional rate of the pongTimeout (default 60s). If an error is returned, the client application should discard the current Websocket connection, as any new writes will be discarded, and new reads will return the same error. Because this function is blocking, it is recommended to wrap it into a goroutine

Example
package main

import (
	"log"
	"time"

	"github.com/lossdev/websockit"
)

func main() {
	// you should have a *websockit.WebsocketServer / *websockit.WebsocketClient already initialized
	var ws websockit.WebsocketClient

	pingOpts := []websockit.ClientPingOption{
		websockit.PingWithPongTimeout(10 * time.Second),
		websockit.PingWithPongLog(true),
	}
	ws.EnableServerPings(pingOpts...)

	go func() {
		if err := ws.ServerPingLoop(); err != nil {
			log.Println(err)
		}
	}()
}
Output:

type WebsocketClientOption

type WebsocketClientOption func(*Websocket)

WebsocketClientOption specifies any custom options a client websocket connection should have

func ClientWithHandshakeTimeout

func ClientWithHandshakeTimeout(t time.Duration) WebsocketClientOption

ClientWithHandshakeTimeout sets a timeout duration for the websocket handshake

func ClientWithProxy

func ClientWithProxy(proxyFunc func(*http.Request) (*url.URL, error)) WebsocketClientOption

ClientWithProxy takes a proxy func and runs each new http.Request through this func

func ClientWithReadBufferSize

func ClientWithReadBufferSize(bufferSize int) WebsocketClientOption

ClientWithReadBufferSize sets the size limit (in bytes) of read buffers in the websocket

func ClientWithSubprotocols

func ClientWithSubprotocols(protocols []string) WebsocketClientOption

ClientWithSubprotocols should be used to set the client's preferred subprotocols

func ClientWithTLSConfig

func ClientWithTLSConfig(t *tls.Config) WebsocketClientOption

ClientWithTLSConfig sets the TLS config for the websocket session

func ClientWithWriteBufferSize

func ClientWithWriteBufferSize(bufferSize int) WebsocketClientOption

ClientWithWriteBufferSize sets the size limit (in bytes) of write buffers in the websocket

type WebsocketServer

type WebsocketServer struct {
	*Websocket
}

WebsocketServer inherits the Websocket fields and methods, and implements its own unique methods

type WebsocketServerOption

type WebsocketServerOption func(*Websocket)

WebsocketServerOption specifies any custom options a server websocket connection should have

func ServerWithCheckOriginFunc

func ServerWithCheckOriginFunc(originFunc func(r *http.Request) bool) WebsocketServerOption

ServerWithCheckOriginFunc can override the default CheckOrigin deny policy given the http.Request made to the server

func ServerWithErrorFunc

func ServerWithErrorFunc(errorFunc func(wr http.ResponseWriter, req *http.Request, status int, reason error)) WebsocketServerOption

ServerWithErrorFunc can use a custom HTTP error function - otherwise, http.Error will print errors

func ServerWithHandshakeTimeout

func ServerWithHandshakeTimeout(t time.Duration) WebsocketServerOption

ServerWithHandshakeTimeout sets a timeout duration for the websocket handshake

func ServerWithReadBufferSize

func ServerWithReadBufferSize(bufferSize int) WebsocketServerOption

ServerWithReadBufferSize sets the size limit (in bytes) of read buffers in the websocket

func ServerWithSubprotocols

func ServerWithSubprotocols(protocols []string) WebsocketServerOption

ServerWithSubprotocols should be used to set the server's preferred subprotocols

func ServerWithWriteBufferSize

func ServerWithWriteBufferSize(bufferSize int) WebsocketServerOption

ServerWithWriteBufferSize sets the size limit (in bytes) of write buffers in the websocket

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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