Documentation
¶
Overview ¶
Package ws provides a typed WebSocket hub with rooms and JSON broadcast on top of github.com/gofiber/contrib/websocket. A hub is in-memory by default; WithRedis bridges broadcasts across replicas via Redis pub/sub.
Index ¶
- Variables
- type Conn
- func (c *Conn[T]) Close()
- func (c *Conn[T]) Join(room string)
- func (c *Conn[T]) Leave(room string)
- func (c *Conn[T]) Locals(key string) any
- func (c *Conn[T]) Params(key string, def ...string) string
- func (c *Conn[T]) Query(key string, def ...string) string
- func (c *Conn[T]) Rooms() []string
- func (c *Conn[T]) Send(msg T) error
- type Handler
- type Hub
- type Option
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ErrClosed = errors.New("ws: connection closed")
ErrClosed is returned when sending on a closed connection.
var ErrSlowClient = errors.New("ws: slow client dropped")
ErrSlowClient is returned when a connection's send buffer is full; the connection is closed and dropped.
Functions ¶
This section is empty.
Types ¶
type Conn ¶
type Conn[T any] struct { // contains filtered or unexported fields }
Conn is one client connection carrying messages of type T.
func (*Conn[T]) Close ¶
func (c *Conn[T]) Close()
Close shuts down the connection. Safe to call multiple times.
type Handler ¶
type Handler[T any] struct { OnConnect func(c *Conn[T]) error // return non-nil to reject the connection OnMessage func(c *Conn[T], msg T) OnDisconnect func(c *Conn[T]) }
Handler holds per-connection lifecycle callbacks (all optional).
type Hub ¶
type Hub[T any] struct { // contains filtered or unexported fields }
Hub tracks connections and rooms for messages of type T.
Example ¶
package main
import (
"github.com/gofiber/fiber/v2"
"github.com/rahmadafandi/fibr/ws"
)
type message struct {
Text string `json:"text"`
}
func main() {
hub := ws.NewHub[message]()
app := fiber.New()
app.Get("/ws/:room", hub.Handle(ws.Handler[message]{
OnConnect: func(c *ws.Conn[message]) error { c.Join(c.Params("room")); return nil },
OnMessage: func(c *ws.Conn[message], m message) { hub.ToRoom(c.Params("room"), m) },
}))
_ = app
}
Output:
func (*Hub[T]) BackplaneErr ¶ added in v0.6.0
BackplaneErr reports a Redis backplane subscription failure, or nil if the backplane is healthy or not configured. A hub with a failed backplane still delivers to its local connections but does not fan out across replicas.
func (*Hub[T]) Broadcast ¶
func (h *Hub[T]) Broadcast(msg T)
Broadcast sends msg to every connection (all replicas if a backplane is set).
type Option ¶
type Option func(*hubConfig)
Option configures a Hub.
func WithPingInterval ¶
WithPingInterval sets the keepalive ping interval (default 30s; 0 disables).
func WithRedis ¶
WithRedis enables a Redis backplane so Broadcast/ToRoom reach clients on all replicas. channel is the pub/sub channel shared by every instance.
func WithSendBuffer ¶
WithSendBuffer sets the per-connection outbound buffer (default 16).