websocket

package
v3.7.1 Latest Latest
Warning

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

Go to latest
Published: Mar 2, 2021 License: MIT Imports: 12 Imported by: 2

Documentation

Index

Constants

View Source
const (
	// NormalClosureMessage the message sent with the close frame
	// during the close handshake.
	NormalClosureMessage = "Server closed connection"
)

Variables

This section is empty.

Functions

func IsCloseError

func IsCloseError(err error) bool

IsCloseError returns true if the error is one of the following close errors: CloseNormalClosure (1000), CloseGoingAway (1001) or CloseNoStatusReceived (1005)

Types

type Conn

type Conn struct {
	*ws.Conn
	// contains filtered or unexported fields
}

Conn represents a WebSocket connection.

func (*Conn) Close

func (c *Conn) Close(code int, message string) error

Close performs the closing handshake as specified by RFC 6455 Section 1.4.

This function expects another goroutine to be reading the connection, expecting the close frame in response. This waiting can time out. If so, Close will just close the connection.

Calling this function multiple times is safe and only the first call will write the close frame to the connection.

func (*Conn) CloseNormal

func (c *Conn) CloseNormal() error

CloseNormal performs the closing handshake as specified by RFC 6455 Section 1.4. Sends status code 1000 (normal closure) and message "Server closed connection".

This function expects another goroutine to be reading the connection, expecting the close frame in response. This waiting can time out. If so, Close will just close the connection.

Calling this function multiple times is safe and only the first call will write the close frame to the connection.

func (*Conn) CloseWithError

func (c *Conn) CloseWithError(err error) error

CloseWithError performs the closing handshake as specified by RFC 6455 Section 1.4 because a server error occurred. Sends status code 1011 (internal server error) and message "Internal server error". If debug is enabled, the message is set to the given error's message.

This function starts another goroutine to read the connection, expecting the close frame in response. This waiting can time out. If so, Close will just close the connection. Therefore, it is not safe to call this function if there is already an active reader.

func (*Conn) GetCloseHandshakeTimeout

func (c *Conn) GetCloseHandshakeTimeout() time.Duration

GetCloseHandshakeTimeout return the timeout used when writing and reading close frames during the close handshake.

func (*Conn) SetCloseHandshakeTimeout

func (c *Conn) SetCloseHandshakeTimeout(timeout time.Duration)

SetCloseHandshakeTimeout set the timeout used when writing and reading close frames during the close handshake.

type ErrorHandler

type ErrorHandler func(request *goyave.Request, err error)

ErrorHandler is a specific Handler type for handling errors returned by websocket Handler.

type Handler

type Handler func(*Conn, *goyave.Request) error

Handler is a handler for websocket connections. The request parameter contains the original upgraded HTTP request.

To keep the connection alive, these handlers should run an infinite for loop that can return on error or exit in a predictable manner.

They also can start goroutines for reads and writes, but shouldn't return before both of them do. The Handler is responsible of synchronizing the goroutines it started, and ensure no reader nor writer are still active when it returns.

When the websocket handler returns, the closing handshake is performed (if not already done using "conn.Close()") and the connection is closed.

If the websocket handler returns nil, it means that everything went fine and the connection can be closed normally. On the other hand, the websocket handler can return an error, such as a write error, to indicate that the connection should not be closed normally. The behavior used when this happens depend on the implementation of the HTTP handler that upgraded the connection.

The following websocket Handler is an example of an "echo" feature using websockets:

func Echo(c *websocket.Conn, request *goyave.Request) error {
	for {
		mt, message, err := c.ReadMessage()
		if err != nil {
			return err
		}
		goyave.Logger.Printf("recv: %s", message)
		err = c.WriteMessage(mt, message)
		if err != nil {
			return fmt.Errorf("write: %w", err)
		}
	}
}

type PanicError

type PanicError struct {
	Reason     error
	Stacktrace string
}

PanicError error sent to the upgrader's ErrorHandler if a panic occurred. If debugging is disabled, the "Stacktrace" field will be empty.

func (*PanicError) Error

func (e *PanicError) Error() string

func (*PanicError) Unwrap

func (e *PanicError) Unwrap() error

Unwrap return the panic reason.

type UpgradeErrorHandler

type UpgradeErrorHandler func(response *goyave.Response, request *goyave.Request, status int, reason error)

UpgradeErrorHandler is a specific Handler type for connection upgrade errors. These handlers are called when an error occurs while the protocol switching.

type Upgrader

type Upgrader struct {
	// UpgradeErrorHandler specifies the function for generating HTTP error responses.
	//
	// The default UpgradeErrorHandler returns a JSON response containing the status text
	// corresponding to the status code returned. If debugging is enabled, the reason error
	// message is returned instead.
	//
	//  {"error": "message"}
	UpgradeErrorHandler UpgradeErrorHandler

	// ErrorHandler specifies the function handling errors returned by websocket Handler.
	// If nil, the error is written to "goyave.ErrLogger". If the error is caused by
	// a panic and debugging is enabled, the default ErrorHandler also writes the stacktrace.
	ErrorHandler ErrorHandler

	// CheckOrigin returns true if the request Origin header is acceptable. If
	// CheckOrigin is nil, then a safe default is used: return false if the
	// Origin request header is present and the origin host is not equal to
	// request Host header.
	//
	// A CheckOrigin function should carefully validate the request origin to
	// prevent cross-site request forgery.
	CheckOrigin func(r *goyave.Request) bool

	// Headers function generating headers to be sent with the protocol switching response.
	Headers func(request *goyave.Request) http.Header

	// Settings the parameters for upgrading the connection. "Error" and "CheckOrigin" are
	// ignored: use the Goyave upgrader's "UpgradeErrorHandler" and "CheckOrigin".
	Settings ws.Upgrader
}

Upgrader is responsible for the upgrade of HTTP connections to websocket connections.

func (*Upgrader) Handler

func (u *Upgrader) Handler(handler Handler) goyave.Handler

Handler create an HTTP handler upgrading the HTTP connection before passing it to the given websocket Handler.

HTTP response's status is set to "101 Switching Protocols".

The connection is closed automatically after the websocket Handler returns, using the closing handshake defined by RFC 6455 Section 1.4 if possible and if not already performed using "conn.Close()".

If the websocket Handler returns an error that is not a CloseError, the Upgrader's error handler will be executed and the close frame sent to the client will have status code 1011 (internal server error) and "Internal server error" as message. If debug is enabled, the message will be set to the one of the error returned by the websocket Handler. Otherwise the close frame will have status code 1000 (normal closure) and "Server closed connection" as a message.

This HTTP handler features a recovery mechanism. If the websocket Handler panics, the connection will be gracefully closed just like if the websocket Handler returned an error without panicking.

This HTTP Handler returns once the connection has been successfully upgraded. That means that, for example, logging middleware will log the request right away instead of waiting for the websocket connection to be closed.

Jump to

Keyboard shortcuts

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