adler

package module
v1.4.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 13, 2026 License: MIT Imports: 12 Imported by: 0

README

Adler

Adler is a lightweight WebSocket server toolkit for Go. It gives you a small, focused API for upgrading HTTP requests, handling sessions, broadcasting messages, and organizing clients into rooms.

Features

  • WebSocket upgrade from net/http
  • Session lifecycle hooks
  • Text, binary, and JSON messaging
  • Protocol-aware JSON or Protobuf serialization (Write, BroadcastAny)
  • Global broadcast, filtered broadcast, and targeted session sends
  • Rooms with join, leave, and room-level broadcast helpers
  • Per-session key-value storage
  • Optional access to the underlying request, protocol, and connection

Roadmap

  • Add a dedicated matchmaker module for queue creation, queue management, and match orchestration.
  • Add ELO-based matchmaking with configurable rating buckets and match quality rules.

Installation

go get github.com/catalinfl/adler

Quick Start

package main

import (
    "log"
    "net/http"

    "github.com/catalinfl/adler"
)

func main() {
    a := adler.New()

    a.HandleConnect(func(s *adler.Session) {
        log.Println("connected:", s.RemoteAddr())
    })

    a.HandleMessage(func(s *adler.Session, msg []byte) {
        _ = s.WriteText([]byte("echo: " + string(msg)))
    })

    a.HandleError(func(s *adler.Session, err error) {
        log.Println("ws error:", err)
    })

    http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
        if err := a.HandleRequest(w, r); err != nil {
            log.Println("handle request:", err)
        }
    })

    log.Fatal(http.ListenAndServe(":8080", nil))
}

How The API Works

1. Create a server

Use adler.New() to build a server instance. You can pass configuration options at construction time:

a := adler.New(
    adler.WithDispatchAsync(true),
    adler.WithMessageBufferSize(256),
    adler.WithPingPeriod(30),
)
2. Register handlers before serving requests

Handlers are set on the Adler instance and are called during the session lifecycle.

  • HandleConnect runs after a session is registered.
  • HandleMessage receives text frames.
  • HandleMessageBinary receives binary frames.
  • HandlePong receives pong frames.
  • HandleClose receives close code and reason.
  • HandleSentMessage and HandleSentMessageBinary run after server writes succeed.
  • HandleError receives runtime errors from the session loop.
  • OnRoomJoin and OnRoomLeave receive room membership events.

Example:

a.HandleConnect(func(s *adler.Session) {
    s.Set("userID", "123")
})

a.HandleClose(func(s *adler.Session, code int, reason string) {
    log.Printf("client closed: code=%d reason=%q", code, reason)
})
3. Serve the websocket endpoint

Call HandleRequest from an HTTP handler. It upgrades the connection and blocks until the session ends.

http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
    _ = a.HandleRequest(w, r)
})
4. Work with a Session

Session is the object you receive in callbacks. It exposes message writers and a small key-value store.

Messaging helpers:

  • Write(any) (protocol-aware JSON text or Protobuf binary)
  • WriteText([]byte)
  • WriteTextWithDeadline([]byte, time.Duration)
  • WriteBinary([]byte)
  • WriteBinaryWithDeadline([]byte, time.Duration)
  • WriteJSON(adler.Map)
  • WriteJSONWithDeadline(any, time.Duration)
  • Close(...[]byte)

Protocol-aware helpers (Write, BroadcastAny, Room.BroadcastAny) use the server protocol (JSON by default). Set adler.WithProtocol(adler.Protobuf) to emit protobuf binary frames.

Storage helpers:

  • Set(key, value)
  • SetNX(key, value)
  • Get(key)
  • GetString(key)
  • GetInt(key)
  • GetInt64(key)
  • GetFloat(key)
  • GetBool(key)
  • Has(key)
  • Unset(key)
  • Keys()
  • Values()
  • Clear()
  • Incr(key) and Decr(key) for *int64 counters

Metadata:

  • Request() returns the original HTTP request
  • Protocol() returns the HTTP protocol string used during upgrade
  • LocalAddr() and RemoteAddr() expose the connection addresses
  • Room() returns the current room
  • UnsafeConn() exposes the raw network connection when you need low-level control

Example session storage:

a.HandleConnect(func(s *adler.Session) {
    s.Set("role", "admin")
    s.SetNX("seen", true)
})

a.HandleMessage(func(s *adler.Session, msg []byte) {
    role, _ := s.GetString("role")
    _ = s.WriteText([]byte("role=" + role + " msg=" + string(msg)))
})
5. Broadcast to all or some clients

Use server-level broadcast helpers when you want to send to multiple sessions.

  • Broadcast([]byte) sends text to all connected sessions
  • BroadcastFilter([]byte, func(*Session) bool) sends text to matching sessions
  • BroadcastBinary([]byte) sends binary to all connected sessions
  • BroadcastBinaryFilter([]byte, func(*Session) bool) sends binary to matching sessions
  • BroadcastJSON(adler.Map) broadcasts JSON
  • BroadcastJSONFilter(adler.Map, func(*Session) bool) broadcasts JSON to matching sessions
  • BroadcastAny(any) broadcasts using the configured protocol
  • BroadcastOthers([]byte, *Session) sends to everyone except the target session
  • SendTo([]byte, *Session) sends only to one session

Example:

a.Broadcast([]byte("server says hello"))

a.SendTo([]byte("private message"), session)

a.BroadcastFilter([]byte("admins only"), func(s *adler.Session) bool {
    role, _ := s.GetString("role")
    return role == "admin"
})
6. Group clients in rooms

Rooms help you manage subsets of sessions.

room := a.NewRoom("lobby")

a.HandleConnect(func(s *adler.Session) {
    _ = room.Join(s)
})

room.Broadcast([]byte("welcome to the lobby"))

Room helpers:

  • NewRoom(name) returns an existing room or creates one
  • DeleteRoom(name) removes a room manually when it is empty
  • Name() returns the room name
  • Len() returns the number of members
  • Sessions() returns a snapshot of current members
  • Join(*Session) adds a session to the room
  • Leave(*Session) removes a session
  • OpenRoom() allows joins again
  • CloseRoom() blocks new joins
  • Broadcast, BroadcastBinary, BroadcastFilter, BroadcastBinaryFilter, BroadcastJSON, BroadcastJSONFilter, BroadcastAny
  • BroadcastBinaryOther([]byte, *Session) sends binary to everyone except the target session
7. Matchmaking with the Matchmaker Module

The matchmaker module provides queue-based matchmaking that groups sessions into rooms automatically. It uses a background goroutine to manage queues and ensure fair player distribution.

Features:

  • Non-blocking queue operations: AddToQueue() and RemoveFromQueue() send commands to a worker goroutine
  • Main and waiting queues: Keeps a main queue and an optional waiting queue when the main queue reaches capacity
  • Automatic room creation: Creates Adler rooms when enough players are queued
  • JSON event notifications: Sends events to sessions as they move through the queue

Matchmaker queue events are defined in matchmaker/matchmaking.proto and emitted as protobuf QueueStatus messages. When the Adler protocol is JSON (default), these events are marshaled to the same JSON shapes as before:

  • "queue_joined" - Session added to main queue
  • "wait_queue_joined" - Session added to waiting queue (main is full)
  • "promoted_to_queue" - Session promoted from waiting to main queue
  • "match_found" - Match room created with room_id and player count

Example:

import "github.com/catalinfl/adler/matchmaker"

mm := matchmaking.NewMatchmaker(a, 
    matchmaking.WithRoomSize(4),
    matchmaking.WithQueueLength(20),
)

a.HandleConnect(func(s *adler.Session) {
    _ = mm.AddToQueue(s)
})

a.HandleMessage(func(s *adler.Session, msg []byte) {
    if string(msg) == "leave_queue" {
        mm.RemoveFromQueue(s)
    }
})

// Use adler.WithProtocol(adler.Protobuf) to send queue events as protobuf frames.
8. Close handling

If the client sends a close frame, HandleClose receives the close status code and reason.

a.HandleClose(func(s *adler.Session, code int, reason string) {
    log.Printf("close: code=%d reason=%q", code, reason)
})

Configuration

Use these options with adler.New(...):

  • WithWriteWait(time.Duration) interprets the argument as seconds; WithWriteWait(10) means 10 seconds
  • WithPongWait(time.Duration) interprets the argument as seconds; WithPongWait(60) means 60 seconds, and WithPongWait(0) disables idle disconnects
  • WithPingPeriod(time.Duration) interprets the argument as seconds; WithPingPeriod(54) means 54 seconds
  • WithMessageBufferSize(int) sets the outbound queue size; start with 64-256 and increase only if you hit ErrBufferFull under normal bursts
  • WithDispatchAsync(bool) switches inbound dispatch to goroutine-per-message when enabled
  • WithDeleteRoomOnEmpty(bool) controls automatic room deletion when the last session leaves (default: true)
  • WithProtocol(adler.Protocol) selects adler.JSON (default) or adler.Protobuf for protocol-aware messaging

Notes On Concurrency

  • Session storage is protected by an internal mutex.
  • Server broadcast methods are safe for normal concurrent use.
  • UnsafeConn() bypasses Adler's internal coordination; only use it if you manage access carefully.

Minimal Room Example

room := a.NewRoom("test")

a.HandleConnect(func(s *adler.Session) {
    _ = room.Join(s)
})

room.HandleJoin(func(s *adler.Session) {
    _ = s.WriteText([]byte("joined room"))
})

License

This project is licensed under the MIT License. See LICENSE for the full text.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrKeyNotFound         = errors.New("key does not exist")
	ErrCoreClosed          = errors.New("core is closed")
	ErrNilSession          = errors.New("nil session")
	ErrAlreadyRegistered   = errors.New("session is already registered")
	ErrWriteClosed         = errors.New("write session is closed")
	ErrBufferFull          = errors.New("buffer is full")
	ErrSessionClosed       = errors.New("session is closed")
	ErrTypeAssertionFailed = errors.New("type assertion failed")
	ErrRoomClosed          = errors.New("room is closed")
	ErrCoreExit            = errors.New("cannot exit from core")
	ErrRoomNotFound        = errors.New("room not found")
	ErrRoomNotEmpty        = errors.New("room is not empty")
	ErrProtobufValue       = errors.New("protobuf serializer: value must implement proto.message")
	ErrProtobufTarget      = errors.New("protobuf serializer: target must implement proto.message")
)

Functions

This section is empty.

Types

type Adler

type Adler struct {
	// Config holds runtime behavior knobs used by session read/write loops.
	Config *Config
	// contains filtered or unexported fields
}

Adler is the main websocket server orchestrator. It owns active sessions, rooms and all user-provided callbacks.

func New

func New(options ...Option) *Adler

New initializes a ready-to-use Adler instance. Options override default configuration values in construction order.

func (*Adler) Broadcast

func (a *Adler) Broadcast(msg []byte) error

Broadcast sends a text websocket message to all connected sessions.

func (*Adler) BroadcastAny added in v1.3.0

func (a *Adler) BroadcastAny(v any) error

BroadcastAny marshals v using the configured serializer and broadcasts it to all connected sessions. The serializer determines whether the message is sent as JSON (text) or Protobuf (binary).

func (*Adler) BroadcastBinary

func (a *Adler) BroadcastBinary(msg []byte) error

BroadcastBinary sends a binary websocket message to all connected sessions.

func (*Adler) BroadcastBinaryFilter

func (a *Adler) BroadcastBinaryFilter(msg []byte, fn func(*Session) bool) error

BroadcastBinaryFilter sends a binary websocket message to sessions matching fn.

func (*Adler) BroadcastFilter

func (a *Adler) BroadcastFilter(msg []byte, fn func(*Session) bool) error

BroadcastFilter sends a text websocket message to sessions matching fn.

func (*Adler) BroadcastJSON

func (a *Adler) BroadcastJSON(v Map) error

BroadcastJSON marshals v and broadcasts it as a text websocket message.

func (*Adler) BroadcastJSONFilter

func (a *Adler) BroadcastJSONFilter(v Map, fn func(*Session) bool) error

BroadcastJSONFilter marshals v and broadcasts it as text to sessions matching fn.

func (*Adler) BroadcastOthers

func (a *Adler) BroadcastOthers(msg []byte, s *Session) error

BroadcastOthers sends msg to all connected sessions except s.

func (*Adler) Close

func (a *Adler) Close() error

Close queues a close frame for all sessions and marks the core as closed.

func (*Adler) DeleteRoom added in v1.1.0

func (a *Adler) DeleteRoom(roomName string) error

DeleteRoom removes a room by name when it has no active sessions.

func (*Adler) HandleClose

func (a *Adler) HandleClose(fn func(*Session, int, string))

func (*Adler) HandleConnect

func (a *Adler) HandleConnect(fn func(*Session))

HandleConnect registers a callback triggered when a websocket session starts.

func (*Adler) HandleDisconnect

func (a *Adler) HandleDisconnect(fn func(*Session))

HandleDisconnect registers a callback triggered when a websocket session ends.

func (*Adler) HandleError

func (a *Adler) HandleError(fn func(*Session, error))

HandleError registers the session-level error handler.

func (*Adler) HandleMessage

func (a *Adler) HandleMessage(fn func(*Session, []byte))

HandleMessage registers the text-message handler.

func (*Adler) HandleMessageBinary

func (a *Adler) HandleMessageBinary(fn func(*Session, []byte))

HandleMessageBinary registers the binary-message handler.

func (*Adler) HandlePong

func (a *Adler) HandlePong(fn func(*Session))

HandlePong registers a callback for pong events.

func (*Adler) HandleRequest

func (a *Adler) HandleRequest(w http.ResponseWriter, r *http.Request) error

HandleRequest upgrades the HTTP request to websocket and serves the session. The call blocks until the websocket session exits.

func (*Adler) HandleSentMessage

func (a *Adler) HandleSentMessage(fn func(*Session, []byte))

HandleSentMessage registers a callback for sent text messages.

func (*Adler) HandleSentMessageBinary

func (a *Adler) HandleSentMessageBinary(fn func(*Session, []byte))

HandleSentMessageBinary registers a callback for sent binary messages.

func (*Adler) IsClosed

func (a *Adler) IsClosed() bool

IsClosed reports whether the server core has been closed.

func (*Adler) Len

func (a *Adler) Len() int

Len returns the current number of active sessions.

func (*Adler) NewRoom

func (a *Adler) NewRoom(name string) *Room

NewRoom returns an existing room by name or creates a new one.

func (*Adler) OnRoomJoin

func (a *Adler) OnRoomJoin(fn func(*Session, *Room))

OnRoomJoin registers a callback triggered after a session joins a room.

func (*Adler) OnRoomLeave

func (a *Adler) OnRoomLeave(fn func(*Session, *Room))

OnRoomLeave registers a callback triggered after a session leaves a room.

func (*Adler) Room added in v1.1.0

func (a *Adler) Room(roomName string) (*Room, error)

GetRoom returns the room identified by RoomName

func (*Adler) SendTo

func (a *Adler) SendTo(msg []byte, s *Session) error

SendTo sends msg only to the target session s.

type Config

type Config struct {
	// WriteWait is the maximum duration allowed for a single outbound write.
	// A zero value disables the per-write deadline.
	// Typical values are between 5 and 30 seconds for internet clients.
	WriteWait time.Duration
	// PongWait is the maximum duration to wait for peer activity before the
	// connection is considered stale by higher-level logic.
	// A zero value disables the idle timeout.
	// If enabled, common values are 30-120 seconds.
	PongWait time.Duration
	// PingPeriod defines how often server-side ping frames are sent.
	// Keep it lower than PongWait when PongWait is enabled.
	// A common ratio is PingPeriod = ~80-90% of PongWait.
	PingPeriod time.Duration
	// MessageBufferSize is the per-session outbound queue capacity.
	// Start with 64-256 for chat-like traffic and increase only if you observe
	// ErrBufferFull under normal expected bursts.
	// Higher values increase per-session memory usage.
	// When this value is 0, runtime falls back to a minimal queue.
	MessageBufferSize int
	// DispatchAsync controls inbound message dispatch mode.
	// true dispatches each message on its own goroutine.
	DispatchAsync bool
	// DeleteRoomOnEmpty controls whether rooms are removed automatically
	// when the last session leaves.
	DeleteRoomOnEmpty bool
	// Prefered protocol by server.
	// This is the used protocol in matchmaker and in other structures of Adler.
	Protocol Protocol
}

Config contains runtime tuning knobs for Adler sessions.

Use constructor options (With...) to override individual fields while keeping stable defaults for all other values.

type JSONSerializer added in v1.3.0

type JSONSerializer struct{}

JSONSerializer marshals messages as JSON text messages and unmarshals from JSON.

func (JSONSerializer) Marshal added in v1.3.0

func (JSONSerializer) Marshal(v any) ([]byte, ws.OpCode, error)

Marshal encodes v as JSON and returns it with text opcode.

func (JSONSerializer) Unmarshal added in v1.3.0

func (JSONSerializer) Unmarshal(data []byte, v any) error

Unmarshal decodes JSON data into v.

type Map

type Map map[string]any

type Option

type Option func(*Config)

Option mutates Config during construction.

func WithDeleteRoomOnEmpty added in v1.1.0

func WithDeleteRoomOnEmpty(enabled bool) Option

WithDeleteRoomOnEmpty controls automatic room removal when room size reaches 0.

func WithDispatchAsync

func WithDispatchAsync(dispatch bool) Option

WithDispatchAsync overrides Config.DispatchAsync.

func WithMessageBufferSize

func WithMessageBufferSize(size int) Option

WithMessageBufferSize overrides Config.MessageBufferSize.

func WithPingPeriod

func WithPingPeriod(d time.Duration) Option

WithPingPeriod overrides Config.PingPeriod. d is interpreted as seconds: WithPingPeriod(60) means 60s.

func WithPongWait

func WithPongWait(d time.Duration) Option

WithPongWait overrides Config.PongWait. d is interpreted as seconds: WithPongWait(60) means 60s. Set 0 to disable idle disconnects.

func WithProtocol added in v1.3.0

func WithProtocol(p Protocol) Option

WithProtocol sets the serialization protocol for the Adler instance. Use JSON for text-based messaging or Protobuf for binary protobuf messages.

func WithWriteWait

func WithWriteWait(d time.Duration) Option

WithWriteWait overrides Config.WriteWait. d is interpreted as seconds: WithWriteWait(10) means 10s. Do not pass time.Second-multiplied values here.

type ProtobufSerializer added in v1.3.0

type ProtobufSerializer struct{}

ProtobufSerializer marshals messages as binary protobuf messages and unmarshals from protobuf.

func (ProtobufSerializer) Marshal added in v1.3.0

func (ProtobufSerializer) Marshal(v any) ([]byte, ws.OpCode, error)

Marshal encodes v as binary protobuf and returns it with binary opcode. Returns ErrProtobufValue if v does not implement proto.Message.

func (ProtobufSerializer) Unmarshal added in v1.3.0

func (ProtobufSerializer) Unmarshal(data []byte, v any) error

Unmarshal decodes binary protobuf data into v. Returns ErrProtobufTarget if v does not implement proto.Message.

type Protocol added in v1.3.0

type Protocol int

Protocol defines the serialization format for messages between server and clients.

const (
	// JSON protocol: messages are serialized as JSON text.
	JSON Protocol = iota
	// Protobuf protocol: messages are serialized as binary protobuf.
	Protobuf
	None
)

type Room

type Room struct {
	// contains filtered or unexported fields
}

Room groups sessions under the same logical channel.

func (*Room) Broadcast

func (r *Room) Broadcast(msg []byte)

Broadcast sends a text websocket message to all room sessions.

func (*Room) BroadcastAny added in v1.3.0

func (r *Room) BroadcastAny(v any) error

BroadcastAny marshals v using the configured serializer and broadcasts it to all room sessions. The serializer determines whether the message is sent as JSON (text) or Protobuf (binary).

func (*Room) BroadcastBinary

func (r *Room) BroadcastBinary(msg []byte)

BroadcastBinary sends a binary websocket message to all room sessions.

func (*Room) BroadcastBinaryFilter added in v1.4.1

func (r *Room) BroadcastBinaryFilter(msg []byte, filter func(*Session) bool)

BroadcastBinaryFilter sends a binary websocket message to room sessions matching filter.

func (*Room) BroadcastBinaryOther added in v1.4.1

func (r *Room) BroadcastBinaryOther(msg []byte, s *Session)

BroadcastBinaryOther sends a binary websocket message to all room sessions except for s.

func (*Room) BroadcastFilter

func (r *Room) BroadcastFilter(msg []byte, filter func(*Session) bool)

BroadcastFilter sends a text websocket message to room sessions matching filter.

func (*Room) BroadcastJSON

func (r *Room) BroadcastJSON(v Map) error

BroadcastJSON marshals v and sends it as a text websocket message.

func (*Room) BroadcastJSONFilter

func (r *Room) BroadcastJSONFilter(v Map, filter func(*Session) bool) error

BroadcastJSONFilter marshals v and sends it as text to sessions matching filter.

func (*Room) BroadcastOther added in v1.4.1

func (r *Room) BroadcastOther(msg []byte, s *Session)

BroadcastOther sends a text websocket message to all room sessions excluding for s.

func (*Room) CloseRoom

func (r *Room) CloseRoom()

CloseRoom marks the room as closed for new Join calls.

func (*Room) HandleJoin

func (r *Room) HandleJoin(fn func(*Session))

HandleJoin registers a callback triggered after a session joins the room.

func (*Room) HandleLeave

func (r *Room) HandleLeave(fn func(*Session))

HandleLeave registers a callback triggered after a session leaves the room.

func (*Room) Join

func (r *Room) Join(s *Session) error

Join adds s to the room and removes it from any previous room.

func (*Room) Leave

func (r *Room) Leave(s *Session)

Leave removes s from the room if s is currently a member.

func (*Room) Len

func (r *Room) Len() int

Len returns the number of sessions currently in the room.

func (*Room) Name

func (r *Room) Name() string

Name returns the room identifier.

func (*Room) OpenRoom

func (r *Room) OpenRoom()

OpenRoom marks the room as open for Join calls.

func (*Room) Sessions

func (r *Room) Sessions() []*Session

Sessions returns a snapshot of current room members.

type Serializer added in v1.3.0

type Serializer interface {
	// Marshal converts a value to bytes and returns the appropriate WebSocket opcode.
	Marshal(v any) ([]byte, ws.OpCode, error)
	// Unmarshal decodes bytes into a value.
	Unmarshal(data []byte, v any) error
}

Serializer defines the interface for marshaling and unmarshaling messages in different formats (JSON, Protobuf, etc.) for WebSocket transmission.

type Session

type Session struct {
	// contains filtered or unexported fields
}

Session represents a single WebSocket client connection.

func (*Session) Clear

func (s *Session) Clear()

Clear removes all key-value pairs from the session store.

func (*Session) Close

func (s *Session) Close(msg ...[]byte) error

Close queues a websocket close frame, optionally with a close payload.

func (*Session) Decr

func (s *Session) Decr(key string) (int64, error)

Decr decrements an int64 pointer value stored at key and returns the result.

func (*Session) Get

func (s *Session) Get(key string) (any, error)

Get returns the value stored under key or ErrKeyNotFound.

func (*Session) GetBool

func (s *Session) GetBool(key string) (bool, bool)

GetBool returns the bool value for key and true on success.

func (*Session) GetFloat

func (s *Session) GetFloat(key string) (float64, bool)

GetFloat returns the float64 value for key and true on success.

func (*Session) GetInt

func (s *Session) GetInt(key string) (int, bool)

GetInt returns the int value for key and true on success.

func (*Session) GetInt64

func (s *Session) GetInt64(key string) (int64, bool)

GetInt64 returns the int64 value for key and true on success.

func (*Session) GetString

func (s *Session) GetString(key string) (string, bool)

GetString returns the string value for key and true on success.

func (*Session) Has

func (s *Session) Has(key string) bool

Has reports whether key exists in the session store.

func (*Session) Incr

func (s *Session) Incr(key string) (int64, error)

Incr increments an int64 pointer value stored at key and returns the result.

func (*Session) Keys

func (s *Session) Keys() []string

Keys returns a snapshot of keys currently in the session store.

func (*Session) LocalAddr

func (s *Session) LocalAddr() net.Addr

LocalAddr returns the local network address of the websocket connection.

func (*Session) Protocol

func (s *Session) Protocol() string

Protocol returns the HTTP protocol string from the upgrade request.

func (*Session) RemoteAddr

func (s *Session) RemoteAddr() net.Addr

RemoteAddr returns the remote network address of the websocket connection.

func (*Session) Request

func (s *Session) Request() *http.Request

Request returns the original HTTP request used for websocket upgrade.

func (*Session) Room

func (s *Session) Room() *Room

Room returns the room currently associated with the session.

func (*Session) Set

func (s *Session) Set(key string, value any)

Set ensures session key storage is initialized.

func (*Session) SetNX

func (s *Session) SetNX(key string, value any) bool

SetNX sets key only when it does not already exist. It returns true when the value was written.

func (*Session) UnsafeConn

func (s *Session) UnsafeConn() net.Conn

UnsafeConn exposes the underlying websocket network connection. Callers must coordinate concurrent reads/writes to avoid races.

func (*Session) Unset

func (s *Session) Unset(key string)

Unset removes key from the session store.

func (*Session) Values

func (s *Session) Values() []any

Values returns a snapshot of values currently in the session store.

func (*Session) Write added in v1.3.0

func (s *Session) Write(v any) error

Write marshals v using the configured serializer and queues it as a message. The serializer determines whether the message is sent as JSON (text) or Protobuf (binary).

func (*Session) WriteBinary

func (s *Session) WriteBinary(msg []byte) error

WriteBinary queues a binary message to be sent to the client.

func (*Session) WriteBinaryWithDeadline

func (s *Session) WriteBinaryWithDeadline(msg []byte, deadline time.Duration) error

WriteBinaryWithDeadline queues a binary message with a custom write deadline.

func (*Session) WriteJSON

func (s *Session) WriteJSON(v Map) error

WriteJSON marshals v to JSON and queues it as a text message.

func (*Session) WriteJSONWithDeadline

func (s *Session) WriteJSONWithDeadline(message any, deadline time.Duration) error

WriteJSONWithDeadline queues a JSON payload with a custom write deadline.

func (*Session) WriteText

func (s *Session) WriteText(message []byte) error

WriteText queues a text message to be sent to the client.

func (*Session) WriteTextWithDeadline

func (s *Session) WriteTextWithDeadline(message []byte, deadline time.Duration) error

WriteTextWithDeadline queues a text message with a custom write deadline.

Directories

Path Synopsis
examples
chat command
Package matchmaking provides a queue-driven room allocator on top of Adler.
Package matchmaking provides a queue-driven room allocator on top of Adler.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL