websocket

package module
v0.30.0-dev2 Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2026 License: MIT Imports: 13 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AuthHandler

func AuthHandler[Params, AuthModel any](
	callbacksFunc func() AuthCallbacks[Params, AuthModel],
	authHandler simba.AuthHandler[AuthModel],
	options ...HandlerOption,
) simba.Handler

AuthWebSocketHandler creates an authenticated handler that uses callbacks for WebSocket lifecycle events.

Example usage:

bearerAuth := simba.BearerAuth(authFunc, simba.BearerAuthConfig{...})

app.Router.GET("/ws/chat", simba.AuthWebSocketHandler(
	simba.AuthCallbacks[Params, User]{
		OnConnect: func(ctx context.Context, conn *simba.Connection, params Params, user User) error {
			registry.Add(user.ID, conn)
			return conn.WriteText(fmt.Sprintf("Welcome %s!", user.Name))
		},
		OnMessage: func(ctx context.Context, conn *simba.Connection, msgType simba.MessageType, data []byte, user User) error {
			// Handle message with user context
			return nil
		},
		OnDisconnect: func(ctx context.Context, connID string, params Params, user User, err error) {
			registry.Remove(user.ID, connID)
		},
	},
	bearerAuth,
))

func Handler

func Handler[Params any](callbacksFunc func() Callbacks[Params], options ...HandlerOption) simba.Handler

WebSocketHandler creates a handler that uses callbacks for WebSocket lifecycle events.

Example usage:

app.Router.GET("/ws/echo", simba.WebSocketHandler(
	echoCallbacks,
	simba.WithMiddleware(
		wsMiddleware.TraceID(),
		wsMiddleware.Logger(),
	),
))

Where echoCallbacks is a function:

func echoCallbacks() simba.Callbacks[simbaModels.NoParams] {
	return simba.Callbacks[simbaModels.NoParams]{
		OnMessage: func(ctx context.Context, conn *simba.Connection, data []byte) error {
			return conn.WriteText("Echo: " + string(data))
		},
	}
}

Types

type AuthCallbackHandlerFunc

type AuthCallbackHandlerFunc[Params, AuthModel any] struct {
	// contains filtered or unexported fields
}

AuthWebSocketCallbackHandlerFunc handles authenticated WebSocket connections with callbacks.

func (*AuthCallbackHandlerFunc[Params, AuthModel]) GetAccepts

func (h *AuthCallbackHandlerFunc[Params, AuthModel]) GetAccepts() string

func (*AuthCallbackHandlerFunc[Params, AuthModel]) GetAuthHandler

func (h *AuthCallbackHandlerFunc[Params, AuthModel]) GetAuthHandler() any

func (*AuthCallbackHandlerFunc[Params, AuthModel]) GetAuthModel

func (h *AuthCallbackHandlerFunc[Params, AuthModel]) GetAuthModel() any

func (*AuthCallbackHandlerFunc[Params, AuthModel]) GetHandler

func (h *AuthCallbackHandlerFunc[Params, AuthModel]) GetHandler() any

func (*AuthCallbackHandlerFunc[Params, AuthModel]) GetParams

func (h *AuthCallbackHandlerFunc[Params, AuthModel]) GetParams() any

func (*AuthCallbackHandlerFunc[Params, AuthModel]) GetProduces

func (h *AuthCallbackHandlerFunc[Params, AuthModel]) GetProduces() string

func (*AuthCallbackHandlerFunc[Params, AuthModel]) GetRequestBody

func (h *AuthCallbackHandlerFunc[Params, AuthModel]) GetRequestBody() any

func (*AuthCallbackHandlerFunc[Params, AuthModel]) GetResponseBody

func (h *AuthCallbackHandlerFunc[Params, AuthModel]) GetResponseBody() any

func (*AuthCallbackHandlerFunc[Params, AuthModel]) ServeHTTP

func (h *AuthCallbackHandlerFunc[Params, AuthModel]) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface.

type AuthCallbacks

type AuthCallbacks[Params, AuthModel any] struct {
	// OnConnect is called after the WebSocket upgrade succeeds (optional).
	// The auth parameter contains the authenticated user model.
	// Return an error to reject the connection.
	OnConnect func(ctx context.Context, conn *Connection, params Params, auth AuthModel) error

	// OnMessage is called for each incoming message from the client (required).
	// The auth parameter contains the authenticated user model.
	// Return an error to trigger OnError (if provided) or close the connection.
	OnMessage func(ctx context.Context, conn *Connection, data []byte, auth AuthModel) error

	// OnDisconnect is called when the connection is closed (optional).
	// The connID is provided since the connection is already closed.
	// The err parameter contains the error that caused disconnection (nil for clean close).
	// This is guaranteed to run via defer, making it safe for cleanup.
	OnDisconnect func(ctx context.Context, connID string, params Params, auth AuthModel, err error)

	// OnError is called when an error occurs during OnMessage (optional).
	// Return true to continue processing messages, false to close the connection.
	// If not provided, any error will close the connection.
	OnError func(ctx context.Context, conn *Connection, err error) bool
}

AuthCallbacks defines the lifecycle callbacks for an authenticated WebSocket connection.

Same as WebSocketCallbacks but includes the authenticated user model in each callback.

type CallbackHandlerFunc

type CallbackHandlerFunc[Params any] struct {
	// contains filtered or unexported fields
}

WebSocketCallbackHandlerFunc handles WebSocket connections with callbacks.

func (*CallbackHandlerFunc[Params]) GetAccepts

func (h *CallbackHandlerFunc[Params]) GetAccepts() string

func (*CallbackHandlerFunc[Params]) GetAuthHandler

func (h *CallbackHandlerFunc[Params]) GetAuthHandler() any

func (*CallbackHandlerFunc[Params]) GetAuthModel

func (h *CallbackHandlerFunc[Params]) GetAuthModel() any

func (*CallbackHandlerFunc[Params]) GetHandler

func (h *CallbackHandlerFunc[Params]) GetHandler() any

func (*CallbackHandlerFunc[Params]) GetParams

func (h *CallbackHandlerFunc[Params]) GetParams() any

func (*CallbackHandlerFunc[Params]) GetProduces

func (h *CallbackHandlerFunc[Params]) GetProduces() string

func (*CallbackHandlerFunc[Params]) GetRequestBody

func (h *CallbackHandlerFunc[Params]) GetRequestBody() any

func (*CallbackHandlerFunc[Params]) GetResponseBody

func (h *CallbackHandlerFunc[Params]) GetResponseBody() any

func (*CallbackHandlerFunc[Params]) ServeHTTP

func (h *CallbackHandlerFunc[Params]) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP implements the http.Handler interface.

type Callbacks

type Callbacks[Params any] struct {
	// OnConnect is called after the WebSocket upgrade succeeds (optional).
	// Return an error to reject the connection.
	OnConnect func(ctx context.Context, conn *Connection, params Params) error

	// OnMessage is called for each incoming message from the client (required).
	// Return an error to trigger OnError (if provided) or close the connection.
	OnMessage func(ctx context.Context, conn *Connection, data []byte) error

	// OnDisconnect is called when the connection is closed (optional).
	// The connID is provided since the connection is already closed.
	// The err parameter contains the error that caused disconnection (nil for clean close).
	// This is guaranteed to run via defer, making it safe for cleanup.
	OnDisconnect func(ctx context.Context, connID string, params Params, err error)

	// OnError is called when an error occurs during OnMessage (optional).
	// Return true to continue processing messages, false to close the connection.
	// If not provided, any error will close the connection.
	OnError func(ctx context.Context, conn *Connection, err error) bool
}

Callbacks defines the lifecycle callbacks for a WebSocket connection.

The framework handles protocol details (upgrade, framing, etc.). You handle application logic (authentication, routing, persistence).

type Connection

type Connection struct {
	// ID is a unique identifier (UUID) for this connection.
	// Use this to track connections in external registries.
	ID string
	// contains filtered or unexported fields
}

WebSocketConnection represents an active WebSocket connection. It provides thread-safe methods for sending messages. The ID can be used to reference this connection in external systems (e.g., Redis, database) for multi-instance message routing.

func (*Connection) Close

func (c *Connection) Close() error

Close closes the WebSocket connection.

func (*Connection) WriteBinary

func (c *Connection) WriteBinary(data []byte) error

WriteBinary sends a binary message to the client (thread-safe).

func (*Connection) WriteJSON

func (c *Connection) WriteJSON(v any) error

WriteJSON marshals v to JSON and sends it as a text message (thread-safe).

func (*Connection) WriteText

func (c *Connection) WriteText(msg string) error

WriteText sends a text message to the client (thread-safe).

type HandlerOption

type HandlerOption interface {
	// contains filtered or unexported methods
}

HandlerOption is an option for configuring WebSocket handlers.

func WithMiddleware

func WithMiddleware(middleware ...Middleware) HandlerOption

WithWebsocketMiddleware adds middleware to the WebSocket handler. Middleware runs before each callback invocation, allowing you to enrich the context.

type Middleware

type Middleware func(ctx context.Context) context.Context

Middleware wraps a context to enrich it before callback invocations. Middleware runs before each callback (OnConnect, OnMessage, OnDisconnect, OnError).

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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