ws

package module
v0.0.0-...-9fa99dc Latest Latest
Warning

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

Go to latest
Published: Jan 5, 2017 License: MIT Imports: 10 Imported by: 1

README

go-ws

Websockets in Go made very simple.

Circle CI

See https://godoc.org/github.com/marcuswestin/go-ws.

TODO

  • Allow for multiple calls to UpgradeRequests with different options (E.g CheckOrigin, PingPeriod, etc)

Documentation

Overview

Package ws implements common websocket functionality, such as heartbeats and message data streaming.

Event Handlers

You use this packet primarily by specifying an event handler function, which then gets passed a series of events, such as Connected, TextMessage, and Disconnected.

You can access the event's data either by reading it all right into memory using Event.Text() and Event.Data(), or you can stream the event's data by using it as an io.Reader. Note that all the underlying event data must be read during the duration of its EventHandler function invocation.

Servers

See UpgradeRequests() and its example for server usage.

Clients

See Connect() and its example for client usage.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (

	// WriteWait is the time allowed to write a message to the peer.
	WriteWait = 10 * time.Second

	// PongWait is the time allowed to read the next pong message from the peer.
	PongWait = 60 * time.Second

	// MaxMessageSize is the maximum message size allowed from peer.
	MaxMessageSize = int64(512)

	// ReadBufferSize is the size of websocket upgrader
	ReadBufferSize = 4096

	// WriteBufferSize is the size of websocket upgrader
	WriteBufferSize = 4096

	// HandshakeTimeout specifies the duration for the handshake to complete.
	HandshakeTimeout = time.Duration(0)

	// ConnMaxSendBufferLen is the Maximum number of messages to buffer per
	// connection before SendText and SendBinary starts dropping messages and
	// return ErrorSendFullBuffer.
	ConnMaxSendBufferLen = 64
)
View Source
var (

	// ErrorSendClosedConn is returned by SendText and SendBinary if called
	// on a closed connection.
	ErrorSendClosedConn = errors.New("send on closed connection")

	// ErrorSendFullBuffer is returned by SendText and SendBinary if called
	// on a connection with a full buffer.
	ErrorSendFullBuffer = errors.New("send on connection with full buffer")
)
View Source
var (

	// TextMessage signifies that a text message was received.
	// Use Event.Text() to read the string.
	TextMessage = EventType(1)

	// BinaryMessage signifies that a binary frame was received.
	// Use Event.Data() to read the data.
	BinaryMessage = EventType(2)

	// Connected signifies that the websocket connected.
	// You are online!
	Connected = EventType(3)

	// Disconnected signifies that the websocket disconnected.
	// It should no longer be used.
	Disconnected = EventType(4)

	// NetError signifies that a network error occured.
	// This will always be followed by a Disconnected event.
	// These events can generally be ignored.
	NetError = EventType(5)

	// Error signifies that an unforeseen error occured.
	// This will always be followed by a Disconnected event.
	Error = EventType(6)
)
View Source
var (

	// CheckOrigin will be called by the upgrader on incoming requests to check
	// the origin. If the CheckOrigin function returns false, then the Upgrade
	// method fails the WebSocket handshake with HTTP status 403.
	// If nil, then use a safe default: fail the handshake if the Origin request
	// header is present and not equal to the Host request header.
	CheckOrigin func(r *http.Request) bool

	// ErrorFn specifies the function for generating HTTP error responses.
	// If nil, then http.Error is used to generate the HTTP response.
	ErrorFn func(w http.ResponseWriter, r *http.Request, status int, reason error)
)

Functions

func Connect

func Connect(addr string, eventHandler EventHandler)

Connect opens a websocket connection to the given address, and starts generating events.

Example (Client)
doneChan := make(chan bool)
defer func() { <-doneChan }()

ws.Connect("http://localhost:8087/ws/echo", func(event *ws.Event, conn *ws.Conn) {
	switch event.Type {
	case ws.Connected:
		fmt.Println("- Connected")
		conn.SendText("Hello!")

	case ws.TextMessage:
		text, _ := event.Text()
		fmt.Println("- Received", text)
		conn.SendText("Disconnect me")

	case ws.Disconnected:
		fmt.Println("- Disconnected")
		doneChan <- true
	}
})
Output:

- Connected
- Received Hello!
- Disconnected

func UpgradeHandlerFunc

func UpgradeHandlerFunc(eventHandler EventHandler) http.HandlerFunc

UpgradeHandlerFunc returns a http.HandlerFunc which will upgrade any incoming http websocket upgrade requests to websocket connections matching the given pattern, and then call the event handler function with connection events.

func UpgradeRequests

func UpgradeRequests(pattern string, eventHandler EventHandler)

UpgradeRequests will start upgrading any http requests matching the given pattern. Calling it is equivalent to calling http.HandleFunc(pattern, birect.UpgradeHandlerFunc(eventHandler))

Example (Server)
// Implement an echo server with logging of connection events
ws.UpgradeRequests("/ws/echo", func(event *ws.Event, conn *ws.Conn) {
	switch event.Type {
	case ws.Connected:
		fmt.Println("Client connected:", conn.HTTPRequest.RemoteAddr)

	case ws.TextMessage:
		text, err := event.Text()
		fmt.Println("Echo message:", text, err)
		conn.SendText(text)

	case ws.BinaryMessage:
		data, err := event.Data() // or use `event` as an `io.Reader`
		fmt.Println("Echo binary message of size:", len(data), err)
		conn.SendBinary(data)

	case ws.Error:
		panic("Error! " + event.Error.Error())

	case ws.NetError:
		fmt.Println("Network error:", event.Error)

	case ws.Disconnected:
		fmt.Println("Client disconnected:", conn.HTTPRequest.RemoteAddr)
	}
})
// ws.UpgradeRequests requires a listening http server
go http.ListenAndServe("localhost:8080", nil)
Output:

Types

type Conn

type Conn struct {
	HTTPRequest *http.Request
	// contains filtered or unexported fields
}

Conn is a handle to underlying websocket connections. It allows you to send messages and close the connection, as well as to get info on the underlying HTTP Request.

func (*Conn) Close

func (c *Conn) Close()

Close the connection. Once Close has returned no more messages will be sent. However, the connection's EventHandler function may still generate more events.

func (*Conn) SendBinary

func (c *Conn) SendBinary(data []byte) (err error)

SendBinary sends a binary websocket message and returns an error if the connection has been closed (ErrorSendClosedConn) or if its send buffer is full (ErrorSendFullBuffer).

func (*Conn) SendText

func (c *Conn) SendText(text string) (err error)

SendText sends a text websocket message and returns an error if the connection has been closed (ErrorSendClosedConn) or if its send buffer is full (ErrorSendFullBuffer).

func (*Conn) String

func (c *Conn) String() string

String returns a string representation of the connection, including the underlying HTTP request's URL and remote address

type Event

type Event struct {
	Type  EventType
	Error error
	// contains filtered or unexported fields
}

Event encapsulates the information passed to EventHandlers. Note that Event.Text, Event.Data and Event.Read may only be called during the duriduration of its EventHandler function. As soon as the EventHandler returns, the underlying io.Reader will no longer be valid.

func (*Event) Data

func (e *Event) Data() ([]byte, error)

Data reads the data of the underlying binary message frame and returns it.

func (*Event) Read

func (e *Event) Read(p []byte) (int, error)

Event implements Reader.

func (*Event) String

func (e *Event) String() string

String returns a string representation of Event that is suitable for debugging

func (*Event) Text

func (e *Event) Text() (string, error)

Text reads the data of the underlying text message frame and returns it as a string.

type EventHandler

type EventHandler func(event *Event, conn *Conn)

EventHandler is a function that gets called once for each connection event. Each connection's EventHandler function is guaranteed to be called serially per-connection, but may be called concurrently across multiple connections.

type EventType

type EventType uint8

EventType is the type of websocket event: Connected, TextMessage, BinaryMessage, Error, NetError, Disconnected

func (EventType) String

func (e EventType) String() string

Jump to

Keyboard shortcuts

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