WebSocket
Fiber supports a websocket upgrade middleware. The *Conn
struct has all the functionality from the gorilla/websocket library.
Installation
- go get -u github.com/gofiber/websocket
Signature
- websocket.New(handler func(*Conn), config ...Config) func(*Ctx)
Config
Property | Type | Description | Default |
---|---|---|---|
HandshakeTimeout | time.Duration | Specifies the duration for the handshake to complete. | 0 |
Subprotocols | []string | specifies 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 | []string | Origins is a string slice of origins that are acceptable, by default all origins are allowed. | []string{“*”} |
ReadBufferSize | int | ReadBufferSize specify I/O buffer sizes in bytes. | 1024 |
WriteBufferSize | int | WriteBufferSize specify I/O buffer sizes in bytes. | 1024 |
EnableCompression | bool | EnableCompression specify if the server should attempt to negotiate per message compression (RFC 7692) | false |
Example
- package main
- import
- "github.com/gofiber/fiber"
- "github.com/gofiber/websocket"
- )
- func main() {
- app := fiber.New()
- app.Use(func(c *fiber.Ctx) {
- c.Locals("Hello", "World")
- c.Next()
- })
- app.Get("/ws", websocket.New(func(c *websocket.Conn) {
- fmt.Println(c.Locals("Hello")) // "World"
- // Websocket logic...
- 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) // ws://localhost:3000/ws
- }