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
go get -u github.com/gofiber/websocket
Example
package main
import (
"log"
"github.com/gofiber/fiber"
"github.com/gofiber/websocket"
)
func main() {
app := fiber.New()
app.Use(func(c *fiber.Ctx) {
if websocket.IsWebSocketUpgrade(c) {
c.Locals("allowed", true)
c.Next()
}
})
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))
}