lazyws

package module
v1.0.4 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2019 License: Apache-2.0 Imports: 6 Imported by: 0

README

Lazyws - Go WebSockets for the lazy

Build Status Go Report Card GoDoc

Gorilla's websocket package is great, but it requires you to do a lot of common setup before you can hit the ground running.

This package abstracts away some of the complexities that need to be re-implemented each time you want to use Gorilla's websocket package:

  • Upgrading the client connection
  • Setting up run/write pumps including reading from and writing to the client (using JSON)
  • Setting up ping/pong control messages as well as read/write timeouts
  • Handling client connects/disconnects

Installation

go get github.com/weters/lazyws

Examples

Documentation

Overview

Package lazyws is a light-weight library that makes working with the https://github.com/gorilla/websocket package a little easier.

Overview

Adding websocket support to your web server is very straight forward. You instantiate a new object, implement a couple of callback methods, add the `UpgradeHandler` and then call the `Run()` method in a separate goroutine. That's it.

l := lazyws.New()
l.Connect = func(client *lazyws.Client) { // client has connected }
l.Disconnect = func(client *lazyws.Client) { // client has disconnected }
l.Recv = func(payload *lazyws.RecvPayload) { // server has received a message }
http.HandleFunc("/ws", l.UpgradeHandler)
go l.Run()

You can also implement the `RecvObject` method which should return an initialized object which a client's message can be deserialized into.

type MyObject struct {
	Name string `json:"name"`
	HomePhone string `json:"homePhone"`
	...
}

l.RecvObject = func() interface {
	return &MyObject{}
}

l.Recv = func(payload *lazyws.RecvPayload) {
	myObj := payload.Payload.(*MyObject)
}

If you don't specify a `RecvObject` method, then the client's message will be unmarshalled into a generic `interface{}` object.

Client Values

The *lazyws.Client object has two features that may be beneficial to you. The first is that you can set abritrary data in the client object and it will persist through subsequent calls.

l.Connect = func(client *lazyws.Client) {
    client.SetData(someVal)
}

l.Recv = func(payload *lazyws.RecvPayload) {
    someVal := payload.Client.GetData().(*SomeType)
}

The second feature is that the *lazyws.Client object stores the *http.Request object which can be retrieved using the `Request()` method.

l.Connect = func(client *lazyws.Client) {
    cookies := client.Request().Cookies()
}

Shutting Down the Server

If you call the `Shutdown()` method, each connected client will have its connection closed with a `websocket.CloseNormalClosure` (1000) code. Otherwise, a `websocket.CloseAbnormalClosure` (1006) will be sent.

l.Shutdown()
srv.Close()

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Client

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

Client represents a client that is connected via WebSockets.

func (*Client) Close

func (c *Client) Close()

Close will shutdown the client and stop the readPump and writePump goroutines

func (*Client) GetData

func (c *Client) GetData() interface{}

GetData will return the arbitrarily associated data. It is concurrency-safe.

c.SetData(myData)
... some time later ....
myData, err := c.GetData().(*MyStruct)

func (*Client) RemoteAddr

func (c *Client) RemoteAddr() net.Addr

RemoteAddr will return the remote address of the client.

func (*Client) Request

func (c *Client) Request() *http.Request

Request returns the HTTP request object

func (*Client) Send

func (c *Client) Send(msg interface{})

Send will send a message to the client

func (*Client) SetData

func (c *Client) SetData(data interface{})

SetData allows you to arbitrarily associate data with a client object. This method is concurrency-safe.

type Lazyws

type Lazyws struct {

	// Specifies the max read size in bytes that a message from the client can be.
	MaxMessageSize int64
	// This method will be the callback for when a client connects to the server.
	Connect func(*Client)
	// This method will be the callback for when a client disconnects from the server.
	Disconnect func(*Client)
	// This method is called when the server receives a new message.
	Recv func(*RecvPayload)
	// This method should return the type of message you want the JSON to be unmarshalled into.
	RecvObject func() interface{}
	// Specifies whether debug messages should be outputted using Go's standard logger.
	Debug bool

	// Upgrader is a websocket upgrader
	Upgrader *websocket.Upgrader
	// contains filtered or unexported fields
}

Lazyws represents a WebSocket manager

func New

func New() *Lazyws

New returns a newly created Lazyws object

func (*Lazyws) Broadcast

func (l *Lazyws) Broadcast(msg interface{})

Broadcast will send a message to all connected clients.

func (*Lazyws) Run

func (l *Lazyws) Run()

Run runs the main run-loop. This should be executed on a separate goroutine.

func (*Lazyws) Shutdown

func (l *Lazyws) Shutdown()

Shutdown will stop the run loop

func (*Lazyws) UpgradeHandler

func (l *Lazyws) UpgradeHandler(w http.ResponseWriter, r *http.Request)

UpgradeHandler is a web handler for upgrading the client's connection.

Example:

http.HandleFunc("/ws", l.UpgradeHandler)

type RecvPayload

type RecvPayload struct {
	Client  *Client
	Payload interface{}
}

RecvPayload represents a data structure containing the payload sent from a client as well as the client that sent said payload.

type WsConn

type WsConn interface {
	Close() error
	ReadJSON(interface{}) error
	RemoteAddr() net.Addr
	SetPongHandler(h func(string) error)
	SetReadDeadline(time.Time) error
	SetReadLimit(int64)
	SetWriteDeadline(time.Time) error
	WriteJSON(interface{}) error
	WriteMessage(int, []byte) error
}

WsConn is an interface that represents a client's websocket connection. The methods are derived from Conn object in the github.com/gorilla/websocket package.

Directories

Path Synopsis
examples
chat command
chat_complex command
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

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