gowsal

package module
v0.0.0-...-df613fb Latest Latest
Warning

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

Go to latest
Published: Mar 16, 2021 License: MIT Imports: 15 Imported by: 0

README

gowsal

A light , fast Web Socket Go library , based on gorilla , this is a development from old version of Iris-go

Documentation

Overview

package gowsal provides rich websocket support for the iris web framework.

Source code and other details for the project are available at GitHub:

https://github.com/kataras/iris/tree/master/websocket

Installation

$ go get -u github.com/kataras/iris/websocket

Example code:

package main

import (
	"fmt"

	"github.com/kataras/iris"
	"github.com/kataras/iris/context"

	"github.com/kataras/iris/websocket"
)

func main() {
	app := iris.New()

	app.Get("/", func(ctx context.Context) {
		ctx.ServeFile("websockets.html", false)
	})

	setupWebsocket(app)

	// x2
	// http://localhost:8080
	// http://localhost:8080
	// write something, press submit, see the result.
	app.Run(iris.Addr(":8080"))
}

func setupWebsocket(app *iris.Application) {
	// create our echo websocket server
	ws := websocket.New(websocket.Config{
		ReadBufferSize:  1024,
		WriteBufferSize: 1024,
	})
	ws.OnConnection(handleConnection)

	// register the server's endpoint.
	// see the inline javascript code in the websockets.html,
	// this endpoint is used to connect to the server.
	app.Get("/echo", ws.Handler())

	// serve the javascript built'n client-side library,
	// see websockets.html script tags, this path is used.
	app.Any("/iris-ws.js", func(ctx context.Context) {
		ctx.Write(websocket.ClientSource)
	})
}

func handleConnection(c websocket.Connection) {
	// Read events from browser
	c.On("chat", func(msg string) {
		// Print the message to the console
		fmt.Printf("%s sent: %s\n", c.Context().RemoteAddr(), msg)
		// Write message back to the client message owner:
		// c.Emit("chat", msg)
		c.To(websocket.Broadcast).Emit("chat", msg)
	})
}

Index

Constants

View Source
const (
	// DefaultWebsocketWriteTimeout 0, no timeout
	DefaultWebsocketWriteTimeout = 0
	// DefaultWebsocketReadTimeout 0, no timeout
	DefaultWebsocketReadTimeout = 0
	// DefaultWebsocketPongTimeout 60 * time.Second
	DefaultWebsocketPongTimeout = 60 * time.Second
	// DefaultWebsocketPingPeriod (DefaultPongTimeout * 9) / 10
	DefaultWebsocketPingPeriod = (DefaultWebsocketPongTimeout * 9) / 10
	// DefaultWebsocketMaxMessageSize 1024
	DefaultWebsocketMaxMessageSize = 1024
	// DefaultWebsocketReadBufferSize 4096
	DefaultWebsocketReadBufferSize = 4096
	// DefaultWebsocketWriterBufferSize 4096
	DefaultWebsocketWriterBufferSize = 4096
	// DefaultEvtMessageKey is the default prefix of the underline websocket events
	// that are being established under the hoods.
	//
	// Defaults to "m:".
	// Last character of the prefix should be ':'.
	DefaultEvtMessageKey = "m:"
)
View Source
const (
	// All is the string which the Emitter use to send a message to all.
	All = ""
	// Broadcast is the string which the Emitter use to send a message to all except this connection.
	Broadcast = ";to;all;except;me;"
)
View Source
const CloseMessage = websocket.CloseMessage

CloseMessage denotes a close control message. The optional message payload contains a numeric code and text. Use the FormatCloseMessage function to format a close message payload.

Use the `Connection#Disconnect` instead.

View Source
const (
	// WriteWait is 1 second at the internal implementation,
	// same as here but this can be changed at the future*
	WriteWait = 1 * time.Second
)

Variables

View Source
var (
	ErrInvalidTypeMessage      = errors.New("Invalid Type for message")
	ErrInvalidWebsocketMessage = errors.New("Invalid websocket Message")
)
View Source
var (
	// DefaultIDGenerator returns a random unique for a new connection.
	// Used when config.IDGenerator is nil.
	DefaultIDGenerator = func(context.Context) string {
		id := uuid.NewV4()
		return id.String()
	}
)
View Source
var ErrAlreadyDisconnected = errors.New("already disconnected")

ErrAlreadyDisconnected can be reported on the `Connection#Disconnect` function whenever the caller tries to close the connection when it is already closed by the client or the caller previously.

Functions

This section is empty.

Types

type Config

type Config struct {
	// IDGenerator used to create (and later on, set)
	// an ID for each incoming websocket connections (clients).
	// The request is an input parameter which you can use to generate the ID (from headers for example).
	// If empty then the ID is generated by DefaultIDGenerator: randomString(64)
	IDGenerator func(ctx context.Context) string
	// EvtMessagePrefix is the prefix of the underline websocket events that are being established under the hoods.
	// This prefix is visible only to the javascript side (code) and it has nothing to do
	// with the message that the end-user receives.
	// Do not change it unless it is absolutely necessary.
	//
	// If empty then defaults to []byte("m:").
	EvtMessagePrefix []byte
	// Error is the function that will be fired if any client couldn't upgrade the HTTP connection
	// to a websocket connection, a handshake error.
	Error func(w http.ResponseWriter, r *http.Request, status int, reason error)
	// CheckOrigin a function that is called right before the handshake,
	// if returns false then that client is not allowed to connect with the websocket server.
	CheckOrigin func(r *http.Request) bool
	// HandshakeTimeout specifies the duration for the handshake to complete.
	HandshakeTimeout time.Duration
	// WriteTimeout time allowed to write a message to the connection.
	// 0 means no timeout.
	// Default value is 0
	WriteTimeout time.Duration
	// ReadTimeout time allowed to read a message from the connection.
	// 0 means no timeout.
	// Default value is 0
	ReadTimeout time.Duration
	// PongTimeout allowed to read the next pong message from the connection.
	// Default value is 60 * time.Second
	PongTimeout time.Duration
	// PingPeriod send ping messages to the connection within this period. Must be less than PongTimeout.
	// Default value is 60 *time.Second
	PingPeriod time.Duration
	// MaxMessageSize max message size allowed from connection.
	// Default value is 1024
	MaxMessageSize int64
	// BinaryMessages set it to true in order to denotes binary data messages instead of utf-8 text
	// compatible if you wanna use the Connection's EmitMessage to send a custom binary data to the client, like a native server-client communication.
	// Default value is false
	BinaryMessages bool
	// ReadBufferSize is the buffer size for the connection reader.
	// Default value is 4096
	ReadBufferSize int
	// WriteBufferSize is the buffer size for the connection writer.
	// Default value is 4096
	WriteBufferSize int
	// EnableCompression specify if the server should attempt to negotiate per
	// message compression (RFC 7692). Setting this value to true does not
	// guarantee that compression will be supported. Currently only "no context
	// takeover" modes are supported.
	//
	// Defaults to false and it should be remain as it is, unless special requirements.
	EnableCompression bool

	// Subprotocols specifies the server's supported protocols in order of
	// preference. If this field is set, then the Upgrade method negotiates a
	// subprotocol by selecting the first match in this list with a protocol
	// requested by the client.
	Subprotocols []string
}

Config the websocket server configuration all of these are optional.

func (Config) Validate

func (c Config) Validate() Config

Validate validates the configuration

type Connection

type Connection interface {
	// Emitter implements EmitMessage & Emit
	Emitter
	// Err is not nil if the upgrader failed to upgrade http to websocket connection.
	Err() error

	// ID returns the connection's identifier
	ID() string

	// Server returns the websocket server instance
	// which this connection is listening to.
	//
	// Its connection-relative operations are safe for use.
	Server() *Server

	// Write writes a raw websocket message with a specific type to the client
	// used by ping messages and any CloseMessage types.
	Write(websocketMessageType int, data []byte) error

	// Context returns the (upgraded) context.Context of this connection
	// avoid using it, you normally don't need it,
	// websocket has everything you need to authenticate the user BUT if it's necessary
	// then  you use it to receive user information, for example: from headers
	Context() context.Context

	// OnDisconnect registers a callback which is fired when this connection is closed by an error or manual
	OnDisconnect(DisconnectFunc)
	// OnError registers a callback which fires when this connection occurs an error
	OnError(ErrorFunc)
	// OnPing  registers a callback which fires on each ping
	OnPing(PingFunc)
	// OnPong  registers a callback which fires on pong message received
	OnPong(PongFunc)
	// FireOnError can be used to send a custom error message to the connection
	//
	// It does nothing more than firing the OnError listeners. It doesn't send anything to the client.
	FireOnError(err error)
	// To defines on what "room" (see Join) the server should send a message
	// returns an Emmiter(`EmitMessage` & `Emit`) to send messages.
	To(string) Emitter
	// OnMessage registers a callback which fires when native websocket message received
	OnMessage(NativeMessageFunc)
	// On registers a callback to a particular event which is fired when a message to this event is received
	On(string, MessageFunc)
	// Join registers this connection to a room, if it doesn't exist then it creates a new. One room can have one or more connections. One connection can be joined to many rooms. All connections are joined to a room specified by their `ID` automatically.
	Join(string)
	// IsJoined returns true when this connection is joined to the room, otherwise false.
	// It Takes the room name as its input parameter.
	IsJoined(roomName string) bool
	// Leave removes this connection entry from a room
	// Returns true if the connection has actually left from the particular room.
	Leave(string) bool
	// OnLeave registers a callback which fires when this connection left from any joined room.
	// This callback is called automatically on Disconnected client, because websocket server automatically
	// deletes the disconnected connection from any joined rooms.
	//
	// Note: the callback(s) called right before the server deletes the connection from the room
	// so the connection theoretical can still send messages to its room right before it is being disconnected.
	OnLeave(roomLeaveCb LeaveRoomFunc)
	// Wait starts the pinger and the messages reader,
	// it's named as "Wait" because it should be called LAST,
	// after the "On" events IF server's `Upgrade` is used,
	// otherise you don't have to call it because the `Handler()` does it automatically.
	Wait()
	// Disconnect disconnects the client, close the underline websocket conn and removes it from the conn list
	// returns the error, if any, from the underline connection
	Disconnect() error
	// SetValue sets a key-value pair on the connection's mem store.
	SetValue(key string, value interface{})
	// GetValue gets a value by its key from the connection's mem store.
	GetValue(key string) interface{}
	// GetValueArrString gets a value as []string by its key from the connection's mem store.
	GetValueArrString(key string) []string
	// GetValueString gets a value as string by its key from the connection's mem store.
	GetValueString(key string) string
	// GetValueInt gets a value as integer by its key from the connection's mem store.
	GetValueInt(key string) int
}

Connection is the front-end API that you will use to communicate with the client side

type ConnectionFunc

type ConnectionFunc func(Connection)

ConnectionFunc is the callback which fires when a client/connection is connected to the Server. Receives one parameter which is the Connection

type ConnectionValues

type ConnectionValues []connectionValue

ConnectionValues is the temporary connection's memory store

func (*ConnectionValues) Get

func (r *ConnectionValues) Get(key string) interface{}

Get returns a value based on its key

func (*ConnectionValues) Reset

func (r *ConnectionValues) Reset()

Reset clears the values

func (*ConnectionValues) Set

func (r *ConnectionValues) Set(key string, value interface{})

Set sets a value based on the key

type DisconnectFunc

type DisconnectFunc func()

DisconnectFunc is the callback which is fired when a client/connection closed

type Emitter

type Emitter interface {
	// EmitMessage sends a native websocket message
	EmitMessage([]byte) error
	// Emit sends a message on a particular event
	Emit(string, interface{}) error
}

Emitter is the message/or/event manager

type ErrorFunc

type ErrorFunc (func(error))

ErrorFunc is the callback which fires whenever an error occurs

type LeaveRoomFunc

type LeaveRoomFunc func(roomName string)

LeaveRoomFunc is the callback which is fired when a client/connection leaves from any room. This is called automatically when client/connection disconnected (because websocket server automatically leaves from all joined rooms)

type MessageFunc

type MessageFunc interface{}

MessageFunc is the second argument to the Emitter's Emit functions. A callback which should receives one parameter of type string, int, bool or any valid JSON/Go struct

type NativeMessageFunc

type NativeMessageFunc func([]byte)

NativeMessageFunc is the callback for native websocket messages, receives one []byte parameter which is the raw client's message

type PingFunc

type PingFunc func()

PingFunc is the callback which fires each ping

type PongFunc

type PongFunc func()

PongFunc is the callback which fires on pong message received

type Server

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

Server is the websocket Server's implementation.

It listens for websocket clients (either from the javascript client-side or from any websocket implementation). See `OnConnection` , to register a single event which will handle all incoming connections and the `Handler` which builds the upgrader handler that you can register to a route based on an Endpoint.

To serve the built'n javascript client-side library look the `websocket.ClientHandler`.

func New

func New(cfg Config) *Server

New returns a new websocket Server based on a configuration. See `OnConnection` , to register a single event which will handle all incoming connections and the `Handler` which builds the upgrader handler that you can register to a route based on an Endpoint.

To serve the built'n javascript client-side library look the `websocket.ClientHandler`.

func (*Server) Disconnect

func (s *Server) Disconnect(connID string) (err error)

Disconnect force-disconnects a websocket connection based on its connection.ID() What it does? 1. remove the connection from the list 2. leave from all joined rooms 3. fire the disconnect callbacks, if any 4. close the underline connection and return its error, if any.

You can use the connection.Disconnect() instead.

func (*Server) GetConnection

func (s *Server) GetConnection(connID string) Connection

GetConnection returns single connection

func (*Server) GetConnections

func (s *Server) GetConnections() []Connection

GetConnections returns all connections

func (*Server) GetConnectionsByRoom

func (s *Server) GetConnectionsByRoom(roomName string) []Connection

GetConnectionsByRoom returns a list of Connection which are joined to this room.

func (*Server) GetTotalConnections

func (s *Server) GetTotalConnections() (n int)

GetTotalConnections returns the number of total connections

func (*Server) Handler

func (s *Server) Handler() context.Handler

Handler builds the handler based on the configuration and returns it. It should be called once per Server, its result should be passed as a middleware to an iris route which will be responsible to register the websocket's endpoint.

Endpoint is the path which the websocket Server will listen for clients/connections.

To serve the built'n javascript client-side library look the `websocket.ClientHandler`.

func (*Server) IsConnected

func (s *Server) IsConnected(connID string) bool

IsConnected returns true if the connection with that ID is connected to the Server useful when you have defined a custom connection id generator (based on a database) and you want to check if that connection is already connected (on multiple tabs)

func (*Server) IsJoined

func (s *Server) IsJoined(roomName string, connID string) bool

IsJoined reports if a specific room has a specific connection into its values. First parameter is the room name, second is the connection's id.

It returns true when the "connID" is joined to the "roomName".

func (*Server) Join

func (s *Server) Join(roomName string, connID string)

Join joins a websocket client to a room, first parameter is the room name and the second the connection.ID()

You can use connection.Join("room name") instead.

func (*Server) Leave

func (s *Server) Leave(roomName string, connID string) bool

Leave leaves a websocket client from a room, first parameter is the room name and the second the connection.ID()

You can use connection.Leave("room name") instead. Returns true if the connection has actually left from the particular room.

func (*Server) LeaveAll

func (s *Server) LeaveAll(connID string)

LeaveAll kicks out a connection from ALL of its joined rooms

func (*Server) OnConnection

func (s *Server) OnConnection(cb ConnectionFunc)

OnConnection is the main event you, as developer, will work with each of the websocket connections.

func (*Server) Upgrade

func (s *Server) Upgrade(ctx context.Context) Connection

Upgrade upgrades the HTTP Server connection to the WebSocket protocol.

The responseHeader is included in the response to the client's upgrade request. Use the responseHeader to specify cookies (Set-Cookie) and the application negotiated subprotocol (Sec--Protocol).

If the upgrade fails, then Upgrade replies to the client with an HTTP error response and the return `Connection.Err()` is filled with that error.

For a more high-level function use the `Handler()` and `OnConnecton` events. This one does not starts the connection's writer and reader, so after your `On/OnMessage` events registration the caller has to call the `Connection#Wait` function, otherwise the connection will be not handled.

type UnderlineConnection

type UnderlineConnection interface {
	// SetWriteDeadline sets the write deadline on the underlying network
	// connection. After a write has timed out, the websocket state is corrupt and
	// all future writes will return an error. A zero value for t means writes will
	// not time out.
	SetWriteDeadline(t time.Time) error
	// SetReadDeadline sets the read deadline on the underlying network connection.
	// After a read has timed out, the websocket connection state is corrupt and
	// all future reads will return an error. A zero value for t means reads will
	// not time out.
	SetReadDeadline(t time.Time) error
	// SetReadLimit sets the maximum size for a message read from the peer. If a
	// message exceeds the limit, the connection sends a close frame to the peer
	// and returns ErrReadLimit to the application.
	SetReadLimit(limit int64)
	// SetPongHandler sets the handler for pong messages received from the peer.
	// The appData argument to h is the PONG frame application data. The default
	// pong handler does nothing.
	SetPongHandler(h func(appData string) error)
	// SetPingHandler sets the handler for ping messages received from the peer.
	// The appData argument to h is the PING frame application data. The default
	// ping handler sends a pong to the peer.
	SetPingHandler(h func(appData string) error)
	// WriteControl writes a control message with the given deadline. The allowed
	// message types are CloseMessage, PingMessage and PongMessage.
	WriteControl(messageType int, data []byte, deadline time.Time) error
	// WriteMessage is a helper method for getting a writer using NextWriter,
	// writing the message and closing the writer.
	WriteMessage(messageType int, data []byte) error
	// ReadMessage is a helper method for getting a reader using NextReader and
	// reading from that reader to a buffer.
	ReadMessage() (messageType int, p []byte, err error)
	// NextWriter returns a writer for the next message to send. The writer's Close
	// method flushes the complete message to the network.
	//
	// There can be at most one open writer on a connection. NextWriter closes the
	// previous writer if the application has not already done so.
	NextWriter(messageType int) (io.WriteCloser, error)
	// Close closes the underlying network connection without sending or waiting for a close frame.
	Close() error
}

UnderlineConnection is the underline connection, nothing to think about, it's used internally mostly but can be used for extreme cases with other libraries.

Jump to

Keyboard shortcuts

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