ws

package
v0.12.5 Latest Latest
Warning

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

Go to latest
Published: Mar 4, 2020 License: MIT Imports: 21 Imported by: 1

Documentation

Overview

Package ws is a WebSocket library for aah framework (RFC 6455 compliant).

aah ws internally it uses tiny, efficient WebSocket library (http://github.com/gobwas/ws) developed by Sergey Kamardin (https://github.com/gobwas).

Index

Constants

View Source
const (
	// EventOnPreConnect event published before connection gets upgraded to WebSocket.
	// It provides a control of accepting incoming request or reject it
	// using ctx.Abort(errorCode).
	EventOnPreConnect = "OnPreConnect"

	// EventOnPostConnect event published right after the successful WebSocket
	// connection which is established with the aah server.
	EventOnPostConnect = "OnPostConnect"

	// EventOnPostDisconnect event published right after the WebSocket client
	// got disconnected. It could have occurred due to graceful disconnect,
	// network related error, etc.
	EventOnPostDisconnect = "OnPostDisconnect"

	// EventOnError event published whenever error occurs in the lifecycle
	// such as Origin Check failed, WebSocket/WebSocket Action not found,
	// WebSocket Action parameter parse error, and WebSocket upgrade fails.
	//
	//`ctx.ErrorReason()` method can be called to know the reason for the error.
	EventOnError = "OnError"
)

Variables

View Source
var (
	ErrOriginMismatch        = errors.New("aahws: origin mismatch")
	ErrParameterParseFailed  = errors.New("aahws: parameter parse failed")
	ErrNotFound              = errors.New("aahws: not found")
	ErrConnectFailed         = errors.New("aahws: connect failed")
	ErrAbortRequest          = errors.New("aahws: abort request")
	ErrConnectionClosed      = errors.New("aahws: connection closed")
	ErrUseOfClosedConnection = errors.New("aahws: use of closed ws connection")
)

WebSocket errors

Functions

func IsDisconnected

func IsDisconnected(err error) bool

IsDisconnected method is helper to identify error is disconnect related. If it is returns true otherwise false.

Types

type Context

type Context struct {
	Req    *Request
	Conn   net.Conn
	Header http.Header // These headers are sent to WS client during Connection upgrade
	// contains filtered or unexported fields
}

Context struct holds friendly WebSocket implementation for aah framework.

func (*Context) Abort

func (ctx *Context) Abort(httpErroCode int)

Abort method is useful for `OnPreConnect` event, aah user could make a choice of proceed or abort.

For e.g.:

ctx.Abort(http.StatusUnauthorized)
ctx.Abort(http.StatusForbidden)

func (*Context) Disconnect

func (ctx *Context) Disconnect() error

Disconnect method disconnects the WebSocket connection immediately. Could be used for force disconnect client from server-side.

Note: After this call, any read/reply will result in error. Since connection already closed from server side.

func (*Context) ErrorReason

func (ctx *Context) ErrorReason() error

ErrorReason method returns error info if error was occurred otherwise nil.

func (*Context) Log

func (ctx *Context) Log() log.Loggerer

Log method adds field WebSocket `Request ID` into current log context and returns the logger.

func (*Context) ReadBinary

func (ctx *Context) ReadBinary() ([]byte, error)

ReadBinary method reads a binary data from WebSocket client.

func (*Context) ReadJSON

func (ctx *Context) ReadJSON(t interface{}) error

ReadJSON method reads JSON data from WebSocket client and does unmarshal into given object.

func (*Context) ReadText

func (ctx *Context) ReadText() (string, error)

ReadText method reads a text value from WebSocket client.

Note: Method does HTML sanatize internally. Refer to `html.EscapeString`.

func (*Context) ReadXML

func (ctx *Context) ReadXML(t interface{}) error

ReadXML method reads XML data from WebSocket client and does unmarshal into given object.

func (*Context) ReplyBinary

func (ctx *Context) ReplyBinary(v []byte) error

ReplyBinary method sends Binary data to the WebSocket client returns error if client is gone, network error, etc.

func (*Context) ReplyJSON

func (ctx *Context) ReplyJSON(v interface{}) error

ReplyJSON method sends JSON data to the WebSocket client returns error if json marshal issue, client is gone, network issue, etc.

func (*Context) ReplyText

func (ctx *Context) ReplyText(v string) error

ReplyText method sends Text data to the WebSocket client returns error if client is gone, network error, etc.

func (*Context) ReplyXML

func (ctx *Context) ReplyXML(v interface{}) error

ReplyXML method sends XML data to the WebSocket client returns error if XML marshal issue, client is gone, network issue, etc.

type Engine

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

Engine struct holds the implementation of WebSocket for aah framework.

func New

func New(app interface{}) (*Engine, error)

New method creates aah WebSocket engine with given aah application instance :)

func (*Engine) AddWebSocket

func (e *Engine) AddWebSocket(t interface{}, methods []*ainsp.Method)

AddWebSocket method adds the given WebSocket implementation into engine.

func (*Engine) Handle

func (e *Engine) Handle(w http.ResponseWriter, r *http.Request)

Handle method primarily does upgrades HTTP connection into WebSocket connection.

Along with Check Origin, aah WebSocket events such as `OnPreConnect`, `OnPostConnect`, `OnPostDisconnect` and `OnError`.

func (*Engine) Log

func (e *Engine) Log() log.Loggerer

Log method provides logging methods at WebSocket engine.

func (*Engine) OnError

func (e *Engine) OnError(ecf EventCallbackFunc)

OnError method sets WebSocket `OnError` event callback into WebSocket engine.

Event published for mismatch origin, action parameter parse error, authentication failure, websocket initial connection failure, websocket not found.

func (*Engine) OnPostConnect

func (e *Engine) OnPostConnect(ecf EventCallbackFunc)

OnPostConnect method sets WebSocket `OnPostConnect` event callback into WebSocket engine.

Event published after each WebSocket connection successfully established.

func (*Engine) OnPostDisconnect

func (e *Engine) OnPostDisconnect(ecf EventCallbackFunc)

OnPostDisconnect method sets WebSocket `OnPostDisconnect` event callback into WebSocket engine.

Event published after each WebSocket connection is disconncted from the aah server.

func (*Engine) OnPreConnect

func (e *Engine) OnPreConnect(ecf EventCallbackFunc)

OnPreConnect method sets WebSocket `OnPreConnect` event callback into WebSocket engine.

Event published before each WebSocket connection been established.

func (*Engine) SetIDGenerator

func (e *Engine) SetIDGenerator(g IDGenerator)

SetIDGenerator method used to set Custom ID generator func for WebSocket connection.

type EventCallbackFunc

type EventCallbackFunc func(eventName string, ctx *Context)

EventCallbackFunc func type used for all WebSocket event callback.

type IDGenerator

type IDGenerator func(ctx *Context) string

IDGenerator func type used to implement custom WebSocket connection ID. By default aah generates GUID using MongoDB Object ID algorithm.

type Request

type Request struct {
	// ID aah assigns Globally Unique Identifier (GUID) using Mongo Object ID
	// algorithm for every WebSocket connection made to aah server.
	//
	// You may use it for tracking, tracing or identifying WebSocket client.
	ID string

	// Host value of the HTTP 'Host' header (e.g. 'example.com:8080').
	Host string

	// Path the request URL Path e.g. `/chatroom/aahframework`.
	Path string

	// Header holds the values of HTTP headers when WebSocket connection made.
	Header http.Header
	// contains filtered or unexported fields
}

Request struct holds information for successful WebSocket connection made.

func (*Request) ClientIP

func (r *Request) ClientIP() string

ClientIP method returns remote Client IP address aka Remote IP. It parses in the order of given set of headers otherwise it uses default default header set `X-Forwarded-For`, `X-Real-IP`, "X-Appengine-Remote-Addr" and finally `http.Request.RemoteAddr`.

func (*Request) PathValue

func (r *Request) PathValue(key string) string

PathValue method returns value for given Path param key otherwise empty string. For eg.: `/discussion/:roomName` => `PathValue("roomName")`.

func (*Request) QueryArrayValue

func (r *Request) QueryArrayValue(key string) []string

QueryArrayValue method returns array value for given URL query param key otherwise empty string slice.

func (*Request) QueryValue

func (r *Request) QueryValue(key string) string

QueryValue method returns value for given URL query param key otherwise empty string.

func (Request) String

func (r Request) String() string

String request stringer interface.

func (*Request) URL

func (r *Request) URL() *url.URL

URL method returns HTTP request URL instance.

Jump to

Keyboard shortcuts

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