websocket

package module
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Apr 19, 2024 License: MIT Imports: 11 Imported by: 126

README


id: websocket

Websocket

Release Discord Test Security Linter

Based on Fasthttp WebSocket for Fiber with available *fiber.Ctx methods like Locals, Params, Query and Cookies.

Note: Requires Go 1.18 and above

Install

go get -u github.com/gofiber/fiber/v2
go get -u github.com/gofiber/contrib/websocket

Signatures

func New(handler func(*websocket.Conn), config ...websocket.Config) fiber.Handler {

Config

Property Type Description Default
Filter func(*fiber.Ctx) bool Defines a function to skip middleware. nil
HandshakeTimeout time.Duration HandshakeTimeout specifies the duration for the handshake to complete. 0 (No timeout)
Subprotocols []string Subprotocols specifies the client's requested subprotocols. nil
Origins []string Allowed Origins based on the Origin header. If empty, everything is allowed. nil
ReadBufferSize int ReadBufferSize specifies the I/O buffer size in bytes for incoming messages. 0 (Use default size)
WriteBufferSize int WriteBufferSize specifies the I/O buffer size in bytes for outgoing messages. 0 (Use default size)
WriteBufferPool websocket.BufferPool WriteBufferPool is a pool of buffers for write operations. nil
EnableCompression bool EnableCompression specifies if the client should attempt to negotiate per message compression (RFC 7692). false
RecoverHandler func(*websocket.Conn) void RecoverHandler is a panic handler function that recovers from panics. defaultRecover

Example

package main

import (
	"log"

	"github.com/gofiber/fiber/v2"
	"github.com/gofiber/contrib/websocket"
)

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

	app.Use("/ws", func(c *fiber.Ctx) error {
		// IsWebSocketUpgrade returns true if the client
		// requested upgrade to the WebSocket protocol.
		if websocket.IsWebSocketUpgrade(c) {
			c.Locals("allowed", true)
			return c.Next()
		}
		return fiber.ErrUpgradeRequired
	})

	app.Get("/ws/:id", websocket.New(func(c *websocket.Conn) {
		// c.Locals is added to the *websocket.Conn
		log.Println(c.Locals("allowed"))  // true
		log.Println(c.Params("id"))       // 123
		log.Println(c.Query("v"))         // 1.0
		log.Println(c.Cookies("session")) // ""

		// websocket.Conn bindings https://pkg.go.dev/github.com/fasthttp/websocket?tab=doc#pkg-index
		var (
			mt  int
			msg []byte
			err error
		)
		for {
			if mt, msg, err = c.ReadMessage(); err != nil {
				log.Println("read:", err)
				break
			}
			log.Printf("recv: %s", msg)

			if err = c.WriteMessage(mt, msg); err != nil {
				log.Println("write:", err)
				break
			}
		}

	}))

	log.Fatal(app.Listen(":3000"))
	// Access the websocket server: ws://localhost:3000/ws/123?v=1.0
	// https://www.websocket.org/echo.html
}

Note with cache middleware

If you get the error websocket: bad handshake when using the cache middleware, please use config.Next to skip websocket path.

app := fiber.New()
app.Use(cache.New(cache.Config{
		Next: func(c *fiber.Ctx) bool {
			return strings.Contains(c.Route().Path, "/ws")
		},
}))

app.Get("/ws/:id", websocket.New(func(c *websocket.Conn) {}))

Note with recover middleware

For internal implementation reasons, currently recover middleware is not work with websocket middleware, please use config.RecoverHandler to add recover handler to websocket endpoints. By default, config RecoverHandler is recovers from panic and writes stack trace to stderr, also returns a response that contains panic message in error field.

app := fiber.New()

app.Use(cache.New(cache.Config{
    Next: func(c *fiber.Ctx) bool {
        return strings.Contains(c.Route().Path, "/ws")
    },
}))

cfg := Config{
    RecoverHandler: func(conn *Conn) {
        if err := recover(); err != nil {
            conn.WriteJSON(fiber.Map{"customError": "error occurred"})
        }
    },
}

app.Get("/ws/:id", websocket.New(func(c *websocket.Conn) {}, cfg))


Documentation

Index

Constants

View Source
const (
	CloseNormalClosure           = 1000
	CloseGoingAway               = 1001
	CloseProtocolError           = 1002
	CloseUnsupportedData         = 1003
	CloseNoStatusReceived        = 1005
	CloseAbnormalClosure         = 1006
	CloseInvalidFramePayloadData = 1007
	ClosePolicyViolation         = 1008
	CloseMessageTooBig           = 1009
	CloseMandatoryExtension      = 1010
	CloseInternalServerErr       = 1011
	CloseServiceRestart          = 1012
	CloseTryAgainLater           = 1013
	CloseTLSHandshake            = 1015
)

Close codes defined in RFC 6455, section 11.7.

View Source
const (
	// TextMessage denotes a text data message. The text message payload is
	// interpreted as UTF-8 encoded text data.
	TextMessage = 1

	// BinaryMessage denotes a binary data message.
	BinaryMessage = 2

	// 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.
	CloseMessage = 8

	// PingMessage denotes a ping control message. The optional message payload
	// is UTF-8 encoded text.
	PingMessage = 9

	// PongMessage denotes a pong control message. The optional message payload
	// is UTF-8 encoded text.
	PongMessage = 10
)

The message types are defined in RFC 6455, section 11.8.

Variables

View Source
var (
	// ErrBadHandshake is returned when the server response to opening handshake is
	// invalid.
	ErrBadHandshake = errors.New("websocket: bad handshake")
	// ErrCloseSent is returned when the application writes a message to the
	// connection after sending a close message.
	ErrCloseSent = errors.New("websocket: close sent")
	// ErrReadLimit is returned when reading a message that is larger than the
	// read limit set for the connection.
	ErrReadLimit = errors.New("websocket: read limit exceeded")
)

Functions

func FormatCloseMessage

func FormatCloseMessage(closeCode int, text string) []byte

FormatCloseMessage formats closeCode and text as a WebSocket close message. An empty message is returned for code CloseNoStatusReceived.

func IsCloseError

func IsCloseError(err error, codes ...int) bool

IsCloseError returns boolean indicating whether the error is a *CloseError with one of the specified codes.

func IsUnexpectedCloseError

func IsUnexpectedCloseError(err error, expectedCodes ...int) bool

IsUnexpectedCloseError returns boolean indicating whether the error is a *CloseError with a code not in the list of expected codes.

func IsWebSocketUpgrade

func IsWebSocketUpgrade(c *fiber.Ctx) bool

IsWebSocketUpgrade returns true if the client requested upgrade to the WebSocket protocol.

func JoinMessages

func JoinMessages(c *websocket.Conn, term string) io.Reader

JoinMessages concatenates received messages to create a single io.Reader. The string term is appended to each message. The returned reader does not support concurrent calls to the Read method.

func New

func New(handler func(*Conn), config ...Config) fiber.Handler

New returns a new `handler func(*Conn)` that upgrades a client to the websocket protocol, you can pass an optional config.

Types

type Config

type Config struct {
	// Filter defines a function to skip middleware.
	// Optional. Default: nil
	Filter func(*fiber.Ctx) bool

	// HandshakeTimeout specifies the duration for the handshake to complete.
	HandshakeTimeout time.Duration

	// Subprotocols specifies the client's requested subprotocols.
	Subprotocols []string

	// Allowed Origin's based on the Origin header, this validate the request origin to
	// prevent cross-site request forgery. Everything is allowed if left empty.
	Origins []string

	// ReadBufferSize and WriteBufferSize specify I/O buffer sizes in bytes. If a buffer
	// size is zero, then a useful default size is used. The I/O buffer sizes
	// do not limit the size of the messages that can be sent or received.
	ReadBufferSize, WriteBufferSize int

	// WriteBufferPool is a pool of buffers for write operations. If the value
	// is not set, then write buffers are allocated to the connection for the
	// lifetime of the connection.
	//
	// A pool is most useful when the application has a modest volume of writes
	// across a large number of connections.
	//
	// Applications should use a single pool for each unique value of
	// WriteBufferSize.
	WriteBufferPool websocket.BufferPool

	// EnableCompression specifies if the client 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.
	EnableCompression bool

	// RecoverHandler is a panic handler function that recovers from panics
	// Default recover function is used when nil and writes error message in a response field `error`
	// It prints stack trace to the stderr by default
	// Optional. Default: defaultRecover
	RecoverHandler func(*Conn)
}

Config ...

type Conn

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

Conn https://godoc.org/github.com/gorilla/websocket#pkg-index

func (*Conn) Cookies

func (conn *Conn) Cookies(key string, defaultValue ...string) string

Cookies is used for getting a cookie value by key Defaults to empty string "" if the cookie doesn't exist. If a default value is given, it will return that value if the cookie doesn't exist.

func (*Conn) Headers

func (conn *Conn) Headers(key string, defaultValue ...string) string

Headers is used for getting a header value by key Defaults to empty string "" if the header doesn't exist. If a default value is given, it will return that value if the header doesn't exist.

func (*Conn) IP added in v1.3.0

func (conn *Conn) IP() string

IP returns the client's network address

func (*Conn) Locals

func (conn *Conn) Locals(key string, value ...interface{}) interface{}

Locals makes it possible to pass interface{} values under string keys scoped to the request and therefore available to all following routes that match the request.

func (*Conn) Params

func (conn *Conn) Params(key string, defaultValue ...string) string

Params is used to get the route parameters. Defaults to empty string "" if the param doesn't exist. If a default value is given, it will return that value if the param doesn't exist.

func (*Conn) Query

func (conn *Conn) Query(key string, defaultValue ...string) string

Query returns the query string parameter in the url. Defaults to empty string "" if the query doesn't exist. If a default value is given, it will return that value if the query doesn't exist.

Jump to

Keyboard shortcuts

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