WebSocket
Based on Fasthttp WebSocket for Fiber with available *fiber.Ctx
methods like Locals, Params, Query and Cookies.
Install
go get -u github.com/gofiber/fiber/v2
go get -u github.com/gofiber/websocket/v2
Example
package main
import (
"log"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/websocket/v2"
)
func main() {
app := fiber.New()
app.Use("/ws", func(c *fiber.Ctx) error {
if websocket.IsWebSocketUpgrade(c) {
c.Locals("allowed", true)
return c.Next()
}
return fiber.ErrUpgradeRequired
})
app.Get("/ws/:id", websocket.New(func(c *websocket.Conn) {
log.Println(c.Locals("allowed"))
log.Println(c.Params("id"))
log.Println(c.Query("v"))
log.Println(c.Cookies("session"))
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"))
}
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) {}))