WebSocket

Fiber supports a websocket upgrade middleware. The *Conn struct has all the functionality from the gorilla/websocket library.

Installation

  1. go get -u github.com/gofiber/websocket

Signature

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

Config

PropertyTypeDescriptionDefault
HandshakeTimeouttime.DurationSpecifies the duration for the handshake to complete.0
Subprotocols[]stringspecifies the server’s supported protocols in order of preference. If this field is not nil, then the Upgrade method negotiates a subprotocol by selecting the first match in this list with a protocol requested by the client.nil
Origins[]stringOrigins is a string slice of origins that are acceptable, by default all origins are allowed.[]string{“*”}
ReadBufferSizeintReadBufferSize specify I/O buffer sizes in bytes.1024
WriteBufferSizeintWriteBufferSize specify I/O buffer sizes in bytes.1024
EnableCompressionboolEnableCompression specify if the server should attempt to negotiate per message compression (RFC 7692)false

Example

  1. package main
  2.  
  3. import
  4. "github.com/gofiber/fiber"
  5. "github.com/gofiber/websocket"
  6. )
  7.  
  8. func main() {
  9. app := fiber.New()
  10.  
  11. app.Use(func(c *fiber.Ctx) {
  12. c.Locals("Hello", "World")
  13. c.Next()
  14. })
  15.  
  16. app.Get("/ws", websocket.New(func(c *websocket.Conn) {
  17. fmt.Println(c.Locals("Hello")) // "World"
  18. // Websocket logic...
  19. for {
  20. mt, msg, err := c.ReadMessage()
  21. if err != nil {
  22. log.Println("read:", err)
  23. break
  24. }
  25. log.Printf("recv: %s", msg)
  26. err = c.WriteMessage(mt, msg)
  27. if err != nil {
  28. log.Println("write:", err)
  29. break
  30. }
  31. }
  32. }))
  33.  
  34. app.Listen(3000) // ws://localhost:3000/ws
  35. }