fiber

package
v0.1.13 Latest Latest
Warning

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

Go to latest
Published: Mar 4, 2026 License: Apache-2.0 Imports: 30 Imported by: 0

Documentation

Overview

Package fiber provides error overlay functionality for development.

Package fiber provides HMR (Hot Module Replacement) support for GoSPA.

Package fiber provides Server-Sent Events (SSE) support for GoSPA applications. SSE enables real-time server-to-client push notifications over HTTP.

Index

Constants

View Source
const SessionTTL = 24 * time.Hour

SessionTTL is how long a session token remains valid (default 24 hours).

Variables

View Source
var (
	ErrInternal     = NewAppError(ErrorCodeInternal, "Internal server error", fiberpkg.StatusInternalServerError)
	ErrNotFound     = NewAppError(ErrorCodeNotFound, "Resource not found", fiberpkg.StatusNotFound)
	ErrBadRequest   = NewAppError(ErrorCodeBadRequest, "Bad request", fiberpkg.StatusBadRequest)
	ErrUnauthorized = NewAppError(ErrorCodeUnauthorized, "Unauthorized", fiberpkg.StatusUnauthorized)
	ErrForbidden    = NewAppError(ErrorCodeForbidden, "Forbidden", fiberpkg.StatusForbidden)
	ErrConflict     = NewAppError(ErrorCodeConflict, "Conflict", fiberpkg.StatusConflict)
	ErrValidation   = NewAppError(ErrorCodeValidation, "Validation error", fiberpkg.StatusBadRequest)
	ErrTimeout      = NewAppError(ErrorCodeTimeout, "Request timeout", fiberpkg.StatusRequestTimeout)
	ErrUnavailable  = NewAppError(ErrorCodeUnavailable, "Service unavailable", fiberpkg.StatusServiceUnavailable)
)

Common errors.

Functions

func BroadcastState

func BroadcastState(hub *WSHub, key string, value interface{}) error

BroadcastState broadcasts state to all connected clients.

func BrotliGzipMiddleware

func BrotliGzipMiddleware(config CompressionConfig) gofiber.Handler

BrotliGzipMiddleware creates a compression middleware with Brotli and Gzip support. Brotli is preferred when supported by the client, falling back to Gzip.

func CORSMiddleware

func CORSMiddleware(allowedOrigins []string) gofiber.Handler

CORSMiddleware handles CORS for API routes. SECURITY: When "*" is in allowedOrigins, Access-Control-Allow-Origin is set to "*" WITHOUT Allow-Credentials (the two are mutually exclusive per the CORS spec). Credentialed access is only enabled for explicitly named origins.

func CSRFSetTokenMiddleware added in v0.1.3

func CSRFSetTokenMiddleware() gofiber.Handler

CSRFSetTokenMiddleware issues and rotates the CSRF cookie on safe HTTP methods. Use this alongside CSRFTokenMiddleware: the setter runs on GETs to rotate the token, the validator runs on mutating methods to verify it. SECURITY: The token is rotated on every GET/HEAD to prevent token fixation attacks.

func CSRFTokenMiddleware

func CSRFTokenMiddleware() gofiber.Handler

CSRFTokenMiddleware validates CSRF tokens on mutating requests. IMPORTANT: Use CSRFSetTokenMiddleware() as well so the token is actually issued.

func DebugMiddleware

func DebugMiddleware(devTools *DevTools) fiberpkg.Handler

DebugMiddleware logs requests and state changes.

func DefaultMessageHandler

func DefaultMessageHandler(client *WSClient, msg WSMessage)

DefaultMessageHandler handles incoming WebSocket messages.

func ErrorHandler

func ErrorHandler(config ErrorHandlerConfig) fiberpkg.ErrorHandler

ErrorHandler creates a Fiber error handler.

func GetComponentID

func GetComponentID(c *gofiber.Ctx, config Config) string

GetComponentID extracts the component ID from context.

func GetIPFromContext added in v0.1.5

func GetIPFromContext(c *fiberpkg.Ctx) string

GetIPFromContext extracts the client IP from the Fiber context. Uses Fiber's built-in IP extraction which handles X-Forwarded-For based on the app's Proxy settings (TrustedProxies, etc).

func GetSessionState

func GetSessionState(c *gofiber.Ctx, config Config) map[string]interface{}

GetSessionState gets or creates session state.

func GetState

func GetState(c *gofiber.Ctx, config Config) *state.StateMap

GetState extracts the state map from context.

func InitStores added in v0.1.4

func InitStores(storage store.Storage)

InitStores updates the global stores to use the provided storage backend.

func IsAppError

func IsAppError(err error) bool

IsAppError checks if an error is an AppError.

func IsSPANavigation

func IsSPANavigation(c *gofiber.Ctx) bool

IsSPANavigation returns true if the current request is an SPA navigation.

func JSONError

func JSONError(c *gofiber.Ctx, status int, message string) error

JSONError sends a JSON error response.

func JSONResponse

func JSONResponse(c *gofiber.Ctx, status int, data interface{}) error

JSONResponse sends a JSON response.

func NotFoundHandler

func NotFoundHandler() fiberpkg.Handler

NotFoundHandler creates a 404 handler.

func PanicHandler

func PanicHandler(config ErrorHandlerConfig) fiberpkg.Handler

PanicHandler creates a panic recovery handler.

func ParseBody

func ParseBody(c *gofiber.Ctx, v interface{}) error

ParseBody parses request body into a struct.

func PreloadHeadersMiddleware

func PreloadHeadersMiddleware(config PreloadConfig) gofiber.Handler

PreloadHeadersMiddleware adds HTTP Link headers for preloading critical resources. This allows browsers to start fetching critical scripts before parsing HTML, reducing time-to-interactive (TTI).

func PreloadHeadersMiddlewareMinimal

func PreloadHeadersMiddlewareMinimal(config PreloadConfig) gofiber.Handler

PreloadHeadersMiddlewareMinimal adds minimal preload headers for micro-runtime. Use this for pages that only need basic reactivity without full SPA features.

func RecoveryMiddleware

func RecoveryMiddleware() gofiber.Handler

RecoveryMiddleware recovers from panics.

func RegisterActionHandler

func RegisterActionHandler(name string, handler ActionHandler)

RegisterActionHandler registers a global action handler.

func RegisterOnConnectHandler

func RegisterOnConnectHandler(handler ConnectHandler)

RegisterOnConnectHandler registers a global connect handler.

func RenderComponent

func RenderComponent(c *gofiber.Ctx, config Config, component templ.Component, componentName string) error

RenderComponent renders a Templ component with state.

func RequestLoggerMiddleware

func RequestLoggerMiddleware() gofiber.Handler

RequestLoggerMiddleware logs requests with method, path, status code, and duration. Output format: [METHOD] /path STATUS duration For structured logging, use Fiber's built-in logger middleware instead.

func RuntimeMiddleware

func RuntimeMiddleware(simple bool) gofiber.Handler

RuntimeMiddleware serves the client runtime script. Uses the embedded runtime from the embed package.

func RuntimeMiddlewareWithContent

func RuntimeMiddlewareWithContent(runtimeContent []byte) gofiber.Handler

RuntimeMiddlewareWithContent serves a custom runtime script. This is provided for advanced use cases where a custom runtime is needed.

func SPAMiddleware

func SPAMiddleware(config Config) gofiber.Handler

SPAMiddleware creates a Fiber middleware for SPA support.

func SPANavigationMiddleware

func SPANavigationMiddleware() gofiber.Handler

SPANavigationMiddleware detects SPA navigation requests and modifies response. When a request has the X-Requested-With: GoSPA-Navigate header, it strips the full HTML shell and returns only the main content for partial page updates.

func SecurityHeadersMiddleware

func SecurityHeadersMiddleware() gofiber.Handler

SecurityHeadersMiddleware adds security headers.

func SendToClient

func SendToClient(hub *WSHub, clientID string, message interface{}) error

SendToClient sends a message to a specific client.

func SetConnectionRateLimiter added in v0.1.6

func SetConnectionRateLimiter(maxTokens float64, refillRate float64)

SetConnectionRateLimiter configures the global connection rate limiter limits.

func SetSessionState

func SetSessionState(c *gofiber.Ctx, config Config, key string, value interface{})

SetSessionState sets session state.

func SetupSSE

func SetupSSE(app *fiberpkg.App, broker *SSEBroker, basePath string, corsConfig *cors.Config)

SetupSSE sets up SSE routes on a Fiber app.

func StateInspectorMiddleware

func StateInspectorMiddleware(devTools *DevTools, config Config) fiberpkg.Handler

StateInspectorMiddleware inspects state changes.

func StateMiddleware

func StateMiddleware(config Config) gofiber.Handler

StateMiddleware creates middleware that injects state into responses.

func StateSyncHandler

func StateSyncHandler(hub *WSHub) fiberpkg.Handler

StateSyncHandler creates a handler for state synchronization.

func WebSocketHandler

func WebSocketHandler(config WebSocketConfig) fiberpkg.Handler

WebSocketHandler creates a WebSocket handler. IMPORTANT: The Hub in config must already be running (go hub.Run()) before calling this. gospa.New() ensures this when EnableWebSocket is true. If you call this directly, start the hub yourself: go config.Hub.Run()

func WebSocketUpgradeMiddleware

func WebSocketUpgradeMiddleware() fiberpkg.Handler

WebSocketUpgradeMiddleware upgrades HTTP connections to WebSocket. It also enforces per-IP rate limiting to prevent connection DoS attacks.

Types

type ActionHandler

type ActionHandler func(client *WSClient, payload json.RawMessage)

ActionHandler is a function that handles a WebSocket action.

func GetActionHandler

func GetActionHandler(name string) (ActionHandler, bool)

GetActionHandler retrieves a global action handler.

type AppError

type AppError struct {
	Code       ErrorCode              `json:"code"`
	Message    string                 `json:"message"`
	Details    map[string]interface{} `json:"details,omitempty"`
	Stack      string                 `json:"stack,omitempty"`
	StatusCode int                    `json:"-"`
	Recover    bool                   `json:"-"` // Whether state can be recovered
}

AppError represents an application error.

func AsAppError

func AsAppError(err error) (*AppError, bool)

AsAppError converts an error to AppError.

func NewAppError

func NewAppError(code ErrorCode, message string, statusCode int) *AppError

NewAppError creates a new application error.

func ValidationError

func ValidationError(field, message string) *AppError

ValidationError creates a validation error.

func ValidationErrors

func ValidationErrors(errors map[string]string) *AppError

ValidationErrors creates a validation error with multiple fields.

func WrapError

func WrapError(err error, code ErrorCode, statusCode int) *AppError

WrapError wraps a generic error into an AppError.

func (*AppError) Error

func (e *AppError) Error() string

Error implements the error interface.

func (*AppError) WithDetails

func (e *AppError) WithDetails(details map[string]interface{}) *AppError

WithDetails adds details to the error.

func (*AppError) WithRecover

func (e *AppError) WithRecover(recover bool) *AppError

WithRecover sets whether state can be recovered.

func (*AppError) WithStack

func (e *AppError) WithStack(stack string) *AppError

WithStack adds a stack trace to the error.

type ClientStateStore

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

ClientStateStore persists client state by client ID for session restoration.

func NewClientStateStore

func NewClientStateStore(storage store.Storage) *ClientStateStore

NewClientStateStore creates a new client state store.

func (*ClientStateStore) Get

func (s *ClientStateStore) Get(clientID string) (*state.StateMap, bool)

Get retrieves a client's state.

func (*ClientStateStore) Remove

func (s *ClientStateStore) Remove(clientID string)

Remove removes a client's state.

func (*ClientStateStore) Save

func (s *ClientStateStore) Save(clientID string, sm *state.StateMap)

Save saves a client's state.

type CompressedContent

type CompressedContent struct {
	Original []byte
	Brotli   []byte
	Gzip     []byte
}

CompressedContent holds original and compressed versions of content.

type CompressionConfig

type CompressionConfig struct {
	// EnableBrotli enables Brotli compression (better compression ratio)
	EnableBrotli bool
	// EnableGzip enables Gzip compression (wider browser support)
	EnableGzip bool
	// BrotliLevel compression level (0-11, default 4 for balance)
	BrotliLevel int
	// GzipLevel compression level (1-9, default 6 for balance)
	GzipLevel int
	// MinSize minimum response size to compress (default 1024 bytes)
	MinSize int
	// CompressibleTypes content types that should be compressed
	CompressibleTypes []string
	// SkipCompression paths to skip compression for
	SkipPaths []string
}

CompressionConfig configures response compression.

func DefaultCompressionConfig

func DefaultCompressionConfig() CompressionConfig

DefaultCompressionConfig returns default compression configuration.

type Config

type Config struct {
	// RuntimeScript is the path to the client runtime script
	RuntimeScript string
	// StateKey is the context key for storing state
	StateKey string
	// ComponentIDKey is the context key for component IDs
	ComponentIDKey string
	// DevMode enables development features
	DevMode bool
	// DefaultState is the initial state for new sessions
	DefaultState map[string]interface{}
}

Config holds the SPA middleware configuration.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default configuration.

type ConnectHandler

type ConnectHandler func(client *WSClient)

ConnectHandler is a function that handles a new WebSocket connection.

type ConnectionRateLimiter added in v0.1.5

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

ConnectionRateLimiter implements per-IP rate limiting for WebSocket connections to prevent DoS attacks. Uses token bucket algorithm with burst capacity. It can optionally use a store.Storage backend (like Redis) for multi-process environments.

func NewConnectionRateLimiter added in v0.1.5

func NewConnectionRateLimiter(storage store.Storage) *ConnectionRateLimiter

NewConnectionRateLimiter creates a rate limiter with sensible defaults.

func (*ConnectionRateLimiter) Allow added in v0.1.5

func (rl *ConnectionRateLimiter) Allow(ip string) bool

Allow checks if a connection from the given IP is allowed. Returns true if the connection should be accepted.

func (*ConnectionRateLimiter) Close added in v0.1.13

func (rl *ConnectionRateLimiter) Close()

Close explicitly stops the rate limiter's cleanup goroutine.

func (*ConnectionRateLimiter) SetStorage added in v0.1.7

func (rl *ConnectionRateLimiter) SetStorage(storage store.Storage)

SetStorage configures the global connection rate limiter to use an external storage backend.

type DevConfig

type DevConfig struct {
	// Enabled enables development mode
	Enabled bool
	// RoutesDir is the directory containing route files
	RoutesDir string
	// ComponentsDir is the directory containing component files
	ComponentsDir string
	// WatchPaths are additional paths to watch for changes
	WatchPaths []string
	// IgnorePaths are paths to ignore
	IgnorePaths []string
	// Debounce is the debounce time for file changes
	Debounce time.Duration
	// OnReload is called when files change
	OnReload func()
	// StateKey is the context key for state
	StateKey string
}

DevConfig holds development configuration.

func DefaultDevConfig

func DefaultDevConfig() DevConfig

DefaultDevConfig returns default development configuration.

type DevTools

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

DevTools provides development tools.

func NewDevTools

func NewDevTools(config DevConfig) *DevTools

NewDevTools creates new development tools.

func (*DevTools) DevPanelHandler

func (d *DevTools) DevPanelHandler() fiberpkg.Handler

DevPanelHandler creates a handler for the dev panel UI.

func (*DevTools) DevToolsHandler

func (d *DevTools) DevToolsHandler() fiberpkg.Handler

DevToolsHandler creates a WebSocket handler for dev tools.

func (*DevTools) GetStateKeys

func (d *DevTools) GetStateKeys() []string

GetStateKeys returns all tracked state keys.

func (*DevTools) GetStateLog

func (d *DevTools) GetStateLog() []StateLogEntry

GetStateLog returns the state change log.

func (*DevTools) LogStateChange

func (d *DevTools) LogStateChange(key string, oldValue, newValue interface{}, source string)

LogStateChange logs a state change.

func (*DevTools) Start

func (d *DevTools) Start()

Start starts the development tools.

func (*DevTools) Stop

func (d *DevTools) Stop()

Stop stops the development tools.

type ErrorCode

type ErrorCode string

ErrorCode represents an error code.

const (
	ErrorCodeInternal     ErrorCode = "INTERNAL_ERROR"
	ErrorCodeNotFound     ErrorCode = "NOT_FOUND"
	ErrorCodeBadRequest   ErrorCode = "BAD_REQUEST"
	ErrorCodeUnauthorized ErrorCode = "UNAUTHORIZED"
	ErrorCodeForbidden    ErrorCode = "FORBIDDEN"
	ErrorCodeConflict     ErrorCode = "CONFLICT"
	ErrorCodeValidation   ErrorCode = "VALIDATION_ERROR"
	ErrorCodeTimeout      ErrorCode = "TIMEOUT"
	ErrorCodeUnavailable  ErrorCode = "SERVICE_UNAVAILABLE"
)

type ErrorHandlerConfig

type ErrorHandlerConfig struct {
	// DevMode enables development features like stack traces
	DevMode bool
	// StateKey is the context key for state
	StateKey string
	// CustomErrorPages maps error codes to custom handlers
	CustomErrorPages map[ErrorCode]func(*fiberpkg.Ctx, *AppError) error
	// OnError is called when an error occurs
	OnError func(*fiberpkg.Ctx, *AppError)
	// RecoverState attempts to recover state on error
	RecoverState bool
}

ErrorHandlerConfig holds error handler configuration.

func DefaultErrorHandlerConfig

func DefaultErrorHandlerConfig() ErrorHandlerConfig

DefaultErrorHandlerConfig returns default error handler configuration.

type ErrorInfo

type ErrorInfo struct {
	Message     string       `json:"message"`
	Type        string       `json:"type"`
	Stack       []StackFrame `json:"stack"`
	File        string       `json:"file"`
	Line        int          `json:"line"`
	Column      int          `json:"column"`
	CodeSnippet string       `json:"codeSnippet"`
	Timestamp   int64        `json:"timestamp"`
	Request     *RequestInfo `json:"request,omitempty"`
	Cause       *ErrorInfo   `json:"cause,omitempty"`
}

ErrorInfo contains information about an error for display.

type ErrorOverlay

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

ErrorOverlay handles error display in development.

func NewErrorOverlay

func NewErrorOverlay(config ErrorOverlayConfig) *ErrorOverlay

NewErrorOverlay creates a new error overlay handler.

func (*ErrorOverlay) RenderOverlay

func (e *ErrorOverlay) RenderOverlay(err error, req *http.Request) string

RenderOverlay renders the error overlay HTML.

type ErrorOverlayConfig

type ErrorOverlayConfig struct {
	Enabled     bool
	ShowStack   bool
	ShowRequest bool
	ShowCode    bool
	Theme       string // "dark" or "light"
	Editor      string // editor to open files in (e.g., "code", "idea")
	EditorPort  int
}

ErrorOverlayConfig configures the error overlay behavior.

func DefaultErrorOverlayConfig

func DefaultErrorOverlayConfig() ErrorOverlayConfig

DefaultErrorOverlayConfig returns the default configuration.

type FileWatcher

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

FileWatcher watches for file changes.

func NewFileWatcher

func NewFileWatcher(config DevConfig) *FileWatcher

NewFileWatcher creates a new file watcher.

func (*FileWatcher) Start

func (w *FileWatcher) Start()

Start starts watching for file changes.

func (*FileWatcher) Stop

func (w *FileWatcher) Stop()

Stop stops watching for file changes.

type HMRConfig

type HMRConfig struct {
	Enabled      bool          `json:"enabled"`
	WatchPaths   []string      `json:"watchPaths"`
	IgnorePaths  []string      `json:"ignorePaths"`
	DebounceTime time.Duration `json:"debounceTime"`
	BroadcastAll bool          `json:"broadcastAll"`
}

HMRConfig configures the HMR system.

type HMRFileChangeEvent

type HMRFileChangeEvent struct {
	Path        string    `json:"path"`
	EventType   string    `json:"eventType"` // "create", "modify", "delete"
	Timestamp   time.Time `json:"timestamp"`
	ContentHash string    `json:"contentHash,omitempty"`
}

HMRFileChangeEvent represents a file change event.

type HMRFileWatcher

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

HMRFileWatcher watches files for changes for HMR.

func NewHMRFileWatcher

func NewHMRFileWatcher(paths, ignore []string, changeChan chan HMRFileChangeEvent) *HMRFileWatcher

NewHMRFileWatcher creates a new HMR file watcher.

func (*HMRFileWatcher) Start

func (fw *HMRFileWatcher) Start()

Start begins watching files.

func (*HMRFileWatcher) Stop

func (fw *HMRFileWatcher) Stop()

Stop stops watching files.

type HMRManager

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

HMRManager manages hot module replacement.

func GetHMR

func GetHMR() *HMRManager

GetHMR returns the global HMR manager.

func InitHMR

func InitHMR(config HMRConfig) *HMRManager

InitHMR initializes the global HMR manager.

func NewHMRManager

func NewHMRManager(config HMRConfig) *HMRManager

NewHMRManager creates a new HMR manager.

func (*HMRManager) Broadcast

func (mgr *HMRManager) Broadcast(msg HMRMessage)

Broadcast sends a message to all connected clients. Failed connections are removed after iteration to avoid mutating the map under RLock.

func (*HMRManager) ClearState

func (mgr *HMRManager) ClearState(moduleID string)

ClearState removes preserved state for a module.

func (*HMRManager) GetState

func (mgr *HMRManager) GetState(moduleID string) (any, bool)

GetState retrieves preserved state for a module.

func (*HMRManager) HMREndpoint

func (mgr *HMRManager) HMREndpoint() fiberpkg.Handler

HMREndpoint returns a Fiber handler for HMR WebSocket.

func (*HMRManager) HMRMiddleware

func (mgr *HMRManager) HMRMiddleware() fiberpkg.Handler

HMRMiddleware returns middleware that adds HMR script to HTML responses.

func (*HMRManager) HandleWebSocket

func (mgr *HMRManager) HandleWebSocket(c *websocket.Conn)

HandleWebSocket handles WebSocket connections for HMR.

func (*HMRManager) PreserveState

func (mgr *HMRManager) PreserveState(moduleID string, state any)

PreserveState saves state for a module.

func (*HMRManager) RegisterClient

func (mgr *HMRManager) RegisterClient(conn *websocket.Conn)

RegisterClient registers a new WebSocket client.

func (*HMRManager) Start

func (mgr *HMRManager) Start()

Start begins HMR operation.

func (*HMRManager) Stop

func (mgr *HMRManager) Stop()

Stop stops HMR operation.

func (*HMRManager) UnregisterClient

func (mgr *HMRManager) UnregisterClient(conn *websocket.Conn)

UnregisterClient removes a WebSocket client.

type HMRMessage

type HMRMessage struct {
	Type      string `json:"type"` // "update", "reload", "error", "state-preserve", "connected"
	Path      string `json:"path,omitempty"`
	ModuleID  string `json:"moduleId,omitempty"`
	Event     string `json:"event,omitempty"`
	State     any    `json:"state,omitempty"`
	Error     string `json:"error,omitempty"`
	Timestamp int64  `json:"timestamp"`
}

HMRMessage represents a message sent to clients.

type HMRUpdatePayload

type HMRUpdatePayload struct {
	ModuleID      string `json:"moduleId"`
	Path          string `json:"path"`
	UpdateType    string `json:"updateType"` // "template", "script", "style", "full"
	Content       string `json:"content,omitempty"`
	StatePreserve bool   `json:"statePreserve"`
}

HMRUpdatePayload contains update information.

type PreloadConfig

type PreloadConfig struct {
	// RuntimeScript is the path to the runtime JS
	RuntimeScript string
	// NavigationScript is the path to the navigation module
	NavigationScript string
	// WebSocketScript is the path to the WebSocket module
	WebSocketScript string
	// CoreScript is the path to the core runtime
	CoreScript string
	// MicroScript is the path to the micro runtime
	MicroScript string
	// Enabled determines if preload headers are added
	Enabled bool
}

PreloadConfig configures preload headers for critical resources.

func DefaultPreloadConfig

func DefaultPreloadConfig() PreloadConfig

DefaultPreloadConfig returns the default preload configuration.

type RequestInfo

type RequestInfo struct {
	Method  string            `json:"method"`
	URL     string            `json:"url"`
	Headers map[string]string `json:"headers,omitempty"`
	Query   map[string]string `json:"query,omitempty"`
}

RequestInfo contains information about the request that caused the error.

type SSEBroker

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

SSEBroker manages SSE connections and event distribution.

func NewSSEBroker

func NewSSEBroker(config *SSEConfig) *SSEBroker

NewSSEBroker creates a new SSE broker.

func (*SSEBroker) Broadcast

func (b *SSEBroker) Broadcast(event SSEEvent) int

Broadcast sends an event to all connected clients.

func (*SSEBroker) BroadcastToTopic

func (b *SSEBroker) BroadcastToTopic(topic string, event SSEEvent) int

BroadcastToTopic sends an event to clients subscribed to a topic.

func (*SSEBroker) ClientCount

func (b *SSEBroker) ClientCount() int

ClientCount returns the number of connected clients.

func (*SSEBroker) Connect

func (b *SSEBroker) Connect(clientID string, metadata ...map[string]any) *SSEClient

Connect registers a new SSE client.

func (*SSEBroker) Disconnect

func (b *SSEBroker) Disconnect(clientID string)

Disconnect removes an SSE client.

func (*SSEBroker) GetClient

func (b *SSEBroker) GetClient(clientID string) (*SSEClient, bool)

GetClient returns a client by ID.

func (*SSEBroker) GetClientsByTopic

func (b *SSEBroker) GetClientsByTopic(topic string) []*SSEClient

GetClientsByTopic returns all clients subscribed to a topic.

func (*SSEBroker) SSEHandler

func (b *SSEBroker) SSEHandler(clientIDFunc func(*fiberpkg.Ctx) string) fiberpkg.Handler

SSEHandler returns a Fiber handler for SSE connections.

func (*SSEBroker) SSESubscribeHandler

func (b *SSEBroker) SSESubscribeHandler() fiberpkg.Handler

SSESubscribeHandler returns a handler for subscribing to topics.

SECURITY WARNING: This handler verifies that the target clientId is connected, but it does NOT verify that the requester IS that client. Any authenticated user who knows another client's ID can subscribe that client to arbitrary topics.

To prevent cross-client topic injection, wrap this handler with authentication middleware that validates req.ClientID against the session identity, e.g.:

sse.Post("/subscribe", authMw, broker.SSESubscribeHandler())

Inside your authMw, reject if the session user ID doesn't match the clientId in the request body.

func (*SSEBroker) SSEUnsubscribeHandler

func (b *SSEBroker) SSEUnsubscribeHandler() fiberpkg.Handler

SSEUnsubscribeHandler returns a handler for unsubscribing from topics.

func (*SSEBroker) Send

func (b *SSEBroker) Send(clientID string, event SSEEvent) bool

Send sends an event to a specific client.

func (*SSEBroker) Subscribe

func (b *SSEBroker) Subscribe(clientID string, topics ...string)

Subscribe adds a client to a topic.

func (*SSEBroker) Unsubscribe

func (b *SSEBroker) Unsubscribe(clientID string, topics ...string)

Unsubscribe removes a client from a topic.

type SSEClient

type SSEClient struct {
	// ID is the unique client identifier
	ID string
	// Channel is the client's event channel
	Channel chan SSEEvent
	// ConnectedAt is the connection timestamp
	ConnectedAt time.Time
	// Metadata contains additional client data
	Metadata map[string]any
	// Topics the client is subscribed to
	Topics map[string]bool
}

SSEClient represents a connected SSE client.

type SSEConfig

type SSEConfig struct {
	// EventBufferSize is the buffer size for client channels
	EventBufferSize int
	// HeartbeatInterval is the keepalive interval (0 to disable)
	HeartbeatInterval time.Duration
	// OnConnect is called when a client connects
	OnConnect func(*SSEClient)
	// OnDisconnect is called when a client disconnects
	OnDisconnect func(*SSEClient)
	// PubSub backend for distributed environments
	PubSub store.PubSub
}

SSEConfig holds SSE broker configuration.

type SSEEvent

type SSEEvent struct {
	// ID is the event identifier
	ID string `json:"id,omitempty"`
	// Event is the event type/name
	Event string `json:"event,omitempty"`
	// Data is the event payload
	Data any `json:"data"`
	// Retry specifies reconnection time in milliseconds
	Retry int `json:"retry,omitempty"`
}

SSEEvent represents a Server-Sent Event.

type SSEHelper

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

SSEHelper provides helper methods for common SSE patterns.

func NewSSEHelper

func NewSSEHelper(broker *SSEBroker) *SSEHelper

NewSSEHelper creates a new SSE helper.

func (*SSEHelper) Alert

func (h *SSEHelper) Alert(clientID string, level string, message string)

Alert sends an alert event.

func (*SSEHelper) AlertAll

func (h *SSEHelper) AlertAll(level string, message string)

AlertAll broadcasts an alert to all clients.

func (*SSEHelper) Notify

func (h *SSEHelper) Notify(clientID string, notification any)

Notify sends a notification event.

func (*SSEHelper) NotifyAll

func (h *SSEHelper) NotifyAll(notification any)

NotifyAll broadcasts a notification to all clients.

func (*SSEHelper) NotifyTopic

func (h *SSEHelper) NotifyTopic(topic string, notification any)

NotifyTopic broadcasts a notification to a topic.

func (*SSEHelper) Progress

func (h *SSEHelper) Progress(clientID string, progress int, message string)

Progress sends a progress event.

func (*SSEHelper) ProgressTopic

func (h *SSEHelper) ProgressTopic(topic string, progress int, message string)

ProgressTopic broadcasts progress to a topic.

func (*SSEHelper) Update

func (h *SSEHelper) Update(clientID string, key string, value any)

Update sends a state update event.

func (*SSEHelper) UpdateAll

func (h *SSEHelper) UpdateAll(key string, value any)

UpdateAll broadcasts a state update to all clients.

func (*SSEHelper) UpdateTopic

func (h *SSEHelper) UpdateTopic(topic string, key string, value any)

UpdateTopic broadcasts a state update to a topic.

type SessionStore

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

SessionStore maps session tokens to client IDs for secure HTTP state sync.

func NewSessionStore

func NewSessionStore(storage store.Storage) *SessionStore

NewSessionStore creates a new session store.

func (*SessionStore) CreateSession

func (s *SessionStore) CreateSession(clientID string) string

CreateSession creates a new session token for a client ID. Returns the session token, or empty string if random generation fails.

func (*SessionStore) RemoveClientSessions

func (s *SessionStore) RemoveClientSessions(clientID string)

RemoveClientSessions removes all sessions for a client ID. NOTE: Depending on the storage backend, this might not be easily achievable without secondary indices. For KV-only stores, this operation shouldn't be relied upon.

func (*SessionStore) RemoveSession

func (s *SessionStore) RemoveSession(token string)

RemoveSession removes a session token.

func (*SessionStore) ValidateSession

func (s *SessionStore) ValidateSession(token string) (string, bool)

ValidateSession returns the client ID for a valid, non-expired session token.

type StackFrame

type StackFrame struct {
	File     string `json:"file"`
	Line     int    `json:"line"`
	Function string `json:"function"`
	Source   string `json:"source,omitempty"`
}

StackFrame represents a single frame in the stack trace.

type StateLogEntry

type StateLogEntry struct {
	Timestamp time.Time   `json:"timestamp"`
	Key       string      `json:"key"`
	OldValue  interface{} `json:"oldValue,omitempty"`
	NewValue  interface{} `json:"newValue"`
	Source    string      `json:"source"` // "client" or "server"
}

StateLogEntry represents a state change log entry.

type StaticCompressionMiddleware

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

StaticCompressionMiddleware serves pre-compressed static files. This is more efficient than on-the-fly compression for static assets.

func NewStaticCompressionMiddleware

func NewStaticCompressionMiddleware(config CompressionConfig) *StaticCompressionMiddleware

NewStaticCompressionMiddleware creates a new static compression middleware.

func (*StaticCompressionMiddleware) CompressStatic

func (s *StaticCompressionMiddleware) CompressStatic(content []byte, contentType string) *CompressedContent

CompressStatic pre-compresses static content and caches it. Use this for embedding static assets that don't change.

func (*StaticCompressionMiddleware) ServeCompressed

func (s *StaticCompressionMiddleware) ServeCompressed(c *gofiber.Ctx, content *CompressedContent, contentType string) error

ServeCompressed serves the best compression for the client.

type StreamingCompressionWriter

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

StreamingCompressionWriter wraps a writer with compression support. Useful for streaming responses like SSE.

func NewBrotliStreamingWriter

func NewBrotliStreamingWriter(w io.Writer, level int) *StreamingCompressionWriter

NewBrotliStreamingWriter creates a streaming Brotli writer.

func NewGzipStreamingWriter

func NewGzipStreamingWriter(w io.Writer, level int) *StreamingCompressionWriter

NewGzipStreamingWriter creates a streaming Gzip writer.

func (*StreamingCompressionWriter) Close

func (w *StreamingCompressionWriter) Close() error

Close closes the compression writer.

func (*StreamingCompressionWriter) Flush

func (w *StreamingCompressionWriter) Flush() error

Flush flushes the compression buffer.

func (*StreamingCompressionWriter) Write

func (w *StreamingCompressionWriter) Write(p []byte) (n int, err error)

Write writes data to the compressed stream.

type WSClient

type WSClient struct {
	ID        string
	SessionID string
	Conn      *websocket.Conn
	Send      chan []byte
	State     *state.StateMap
	// contains filtered or unexported fields
}

WSClient represents a connected WebSocket client.

func NewWSClient

func NewWSClient(id string, conn *websocket.Conn) *WSClient

NewWSClient creates a new WebSocket client.

func (*WSClient) Close

func (c *WSClient) Close()

Close closes the client connection.

func (*WSClient) ReadPump

func (c *WSClient) ReadPump(hub *WSHub, onMessage func(*WSClient, WSMessage))

ReadPump pumps messages from the WebSocket connection to the hub.

func (*WSClient) SendError

func (c *WSClient) SendError(message string)

SendError sends an error message to the client.

func (*WSClient) SendInitWithSession

func (c *WSClient) SendInitWithSession(sessionToken string)

SendInitWithSession sends the initial state with a session token for HTTP state sync.

func (*WSClient) SendJSON

func (c *WSClient) SendJSON(v interface{}) error

SendJSON sends a JSON message to the client.

func (*WSClient) SendState

func (c *WSClient) SendState()

SendState sends the current state to the client. When StateDiffing is enabled it only sends keys that changed since the last successful send — using a "patch" message type that the client merges into its local state rather than replacing it wholesale. When CompressState is enabled the payload JSON is gzip-compressed and base64-encoded, with a "compressed":true flag so the client can decompress.

func (*WSClient) WritePump

func (c *WSClient) WritePump()

WritePump pumps messages from the hub to the WebSocket connection.

type WSHub

type WSHub struct {
	Clients    map[string]*WSClient
	Register   chan *WSClient
	Unregister chan *WSClient
	Broadcast  chan []byte
	// contains filtered or unexported fields
}

WSHub maintains the set of active clients and broadcasts messages.

func NewWSHub

func NewWSHub(pubsub store.PubSub) *WSHub

NewWSHub creates a new WebSocket hub.

func (*WSHub) BroadcastExcept

func (h *WSHub) BroadcastExcept(exceptID string, message []byte)

BroadcastExcept broadcasts to all clients except the specified one.

func (*WSHub) BroadcastTo

func (h *WSHub) BroadcastTo(clientIDs []string, message []byte)

BroadcastTo broadcasts a message to specific clients.

func (*WSHub) ClientCount

func (h *WSHub) ClientCount() int

ClientCount returns the number of connected clients.

func (*WSHub) Close added in v0.1.13

func (h *WSHub) Close()

Close explicitly stops the WSHub loop.

func (*WSHub) GetClient

func (h *WSHub) GetClient(id string) (*WSClient, bool)

GetClient retrieves a client by ID.

func (*WSHub) Run

func (h *WSHub) Run()

Run starts the hub's main loop.

type WSMessage

type WSMessage struct {
	Type         string                 `json:"type"`
	ComponentID  string                 `json:"componentId,omitempty"`
	Action       string                 `json:"action,omitempty"`
	Data         map[string]interface{} `json:"data,omitempty"`
	Payload      json.RawMessage        `json:"payload,omitempty"`
	SessionToken string                 `json:"sessionToken,omitempty"` // SECURITY: Token sent in message, not URL
	ClientID     string                 `json:"clientId,omitempty"`     // Client ID for session association
}

WSMessage represents a WebSocket message.

type WSStateUpdate

type WSStateUpdate struct {
	Key   string      `json:"key"`
	Value interface{} `json:"value"`
}

WSStateUpdate represents a state update message.

type WebSocketConfig

type WebSocketConfig struct {
	// Hub is the WebSocket hub for managing connections.
	Hub *WSHub
	// OnConnect is called when a client connects.
	OnConnect func(*WSClient)
	// OnDisconnect is called when a client disconnects.
	OnDisconnect func(*WSClient)
	// OnMessage is called when a message is received.
	OnMessage func(*WSClient, WSMessage)
	// GenerateID generates a client ID.
	GenerateID func() string
	// CompressState enables gzip compression of outbound state payloads.
	// The client receives { type:'compressed', data: '<base64>', compressed:true }
	// and must decompress using the DecompressionStream browser API.
	CompressState bool
	// StateDiffing enables delta-only 'patch' messages instead of full state syncs.
	// When enabled only changed keys are broadcast after the initial snapshot.
	StateDiffing bool
	// Serializer overrides JSON for outbound state serialization.
	Serializer func(interface{}) ([]byte, error)
	// Deserializer overrides JSON for inbound state deserialization.
	Deserializer func([]byte, interface{}) error
	// WSMaxMessageSize limits the maximum payload size for WebSocket messages.
	WSMaxMessageSize int
}

WebSocketConfig holds WebSocket configuration.

func DefaultWebSocketConfig

func DefaultWebSocketConfig() WebSocketConfig

DefaultWebSocketConfig returns default WebSocket configuration. NOTE: The caller is responsible for starting the hub with `go hub.Run()` before registering the handler. gospa.New() does this automatically when EnableWebSocket is true.

Jump to

Keyboard shortcuts

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