websocket

package module
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: May 12, 2020 License: MIT Imports: 5 Imported by: 10

README

🧬 WebSocket middleware for Fiber

Based on Fasthttp WebSocket.

Install
go get -u github.com/gofiber/fiber
go get -u github.com/gofiber/websocket
Example
package main

import 
  "github.com/gofiber/fiber"
  "github.com/gofiber/websocket"
)

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

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

  app.Get("/ws/:id?", websocket.New(func(c *websocket.Conn) {
    // Locals & Params are added to the *websocket.Conn
    fmt.Println(c.Locals("allowed"))  // true
    fmt.Println(c.Params("id"))       // "1337"

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

  }))

  app.Listen(3000)
  // Access the websocket server: ws://localhost:3000/ws/12345
}

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

This section is empty.

Functions

func IsWebSocketUpgrade

func IsWebSocketUpgrade(ctx *fiber.Ctx) bool

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

func New

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

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
	// 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
}

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) Locals

func (conn *Conn) Locals(key string) 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.

Jump to

Keyboard shortcuts

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