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 ¶
- Variables
- func BroadcastState(hub *WSHub, key string, value interface{}) error
- func BrotliGzipMiddleware(config CompressionConfig) gofiber.Handler
- func CORSMiddleware(allowedOrigins []string) gofiber.Handler
- func CSRFTokenMiddleware() gofiber.Handler
- func DebugMiddleware(devTools *DevTools) fiber.Handler
- func DefaultMessageHandler(client *WSClient, msg WSMessage)
- func ErrorHandler(config ErrorHandlerConfig) fiber.ErrorHandler
- func GetComponentID(c *gofiber.Ctx, config Config) string
- func GetSessionState(c *gofiber.Ctx, config Config) map[string]interface{}
- func GetState(c *gofiber.Ctx, config Config) *state.StateMap
- func IsAppError(err error) bool
- func IsSPANavigation(c *gofiber.Ctx) bool
- func JSONError(c *gofiber.Ctx, status int, message string) error
- func JSONResponse(c *gofiber.Ctx, status int, data interface{}) error
- func NotFoundHandler() fiber.Handler
- func PanicHandler(config ErrorHandlerConfig) fiber.Handler
- func ParseBody(c *gofiber.Ctx, v interface{}) error
- func PreloadHeadersMiddleware(config PreloadConfig) gofiber.Handler
- func PreloadHeadersMiddlewareMinimal(config PreloadConfig) gofiber.Handler
- func RecoveryMiddleware() gofiber.Handler
- func RegisterActionHandler(name string, handler ActionHandler)
- func RegisterOnConnectHandler(handler ConnectHandler)
- func RenderComponent(c *gofiber.Ctx, config Config, component templ.Component, componentName string) error
- func RequestLoggerMiddleware() gofiber.Handler
- func RuntimeMiddleware(simple bool) gofiber.Handler
- func RuntimeMiddlewareWithContent(runtimeContent []byte) gofiber.Handler
- func SPAMiddleware(config Config) gofiber.Handler
- func SPANavigationMiddleware() gofiber.Handler
- func SecurityHeadersMiddleware() gofiber.Handler
- func SendToClient(hub *WSHub, clientID string, message interface{}) error
- func SetSessionState(c *gofiber.Ctx, config Config, key string, value interface{})
- func SetupSSE(app *fiber.App, broker *SSEBroker, basePath string, corsConfig *cors.Config)
- func StateInspectorMiddleware(devTools *DevTools, config Config) fiber.Handler
- func StateMiddleware(config Config) gofiber.Handler
- func StateSyncHandler(hub *WSHub) fiber.Handler
- func WebSocketHandler(config WebSocketConfig) fiber.Handler
- func WebSocketUpgradeMiddleware() fiber.Handler
- type ActionHandler
- type AppError
- type ClientStateStore
- type CompressedContent
- type CompressionConfig
- type Config
- type ConnectHandler
- type DevConfig
- type DevTools
- func (d *DevTools) DevPanelHandler() fiber.Handler
- func (d *DevTools) DevToolsHandler() fiber.Handler
- func (d *DevTools) GetStateKeys() []string
- func (d *DevTools) GetStateLog() []StateLogEntry
- func (d *DevTools) LogStateChange(key string, oldValue, newValue interface{}, source string)
- func (d *DevTools) Start()
- func (d *DevTools) Stop()
- type ErrorCode
- type ErrorHandlerConfig
- type ErrorInfo
- type ErrorOverlay
- type ErrorOverlayConfig
- type FileWatcher
- type HMRConfig
- type HMRFileChangeEvent
- type HMRFileWatcher
- type HMRManager
- func (mgr *HMRManager) Broadcast(msg HMRMessage)
- func (mgr *HMRManager) ClearState(moduleID string)
- func (mgr *HMRManager) GetState(moduleID string) (any, bool)
- func (mgr *HMRManager) HMREndpoint() fiber.Handler
- func (mgr *HMRManager) HMRMiddleware() fiber.Handler
- func (mgr *HMRManager) HandleWebSocket(c *websocket.Conn)
- func (mgr *HMRManager) PreserveState(moduleID string, state any)
- func (mgr *HMRManager) RegisterClient(conn *websocket.Conn)
- func (mgr *HMRManager) Start()
- func (mgr *HMRManager) Stop()
- func (mgr *HMRManager) UnregisterClient(conn *websocket.Conn)
- type HMRMessage
- type HMRUpdatePayload
- type PreloadConfig
- type RequestInfo
- type SSEBroker
- func (b *SSEBroker) Broadcast(event SSEEvent) int
- func (b *SSEBroker) BroadcastToTopic(topic string, event SSEEvent) int
- func (b *SSEBroker) ClientCount() int
- func (b *SSEBroker) Connect(clientID string, metadata ...map[string]any) *SSEClient
- func (b *SSEBroker) Disconnect(clientID string)
- func (b *SSEBroker) GetClient(clientID string) (*SSEClient, bool)
- func (b *SSEBroker) GetClientsByTopic(topic string) []*SSEClient
- func (b *SSEBroker) SSEHandler(clientIDFunc func(*fiber.Ctx) string) fiber.Handler
- func (b *SSEBroker) SSESubscribeHandler() fiber.Handler
- func (b *SSEBroker) SSEUnsubscribeHandler() fiber.Handler
- func (b *SSEBroker) Send(clientID string, event SSEEvent) bool
- func (b *SSEBroker) Subscribe(clientID string, topics ...string)
- func (b *SSEBroker) Unsubscribe(clientID string, topics ...string)
- type SSEClient
- type SSEConfig
- type SSEEvent
- type SSEHelper
- func (h *SSEHelper) Alert(clientID string, level string, message string)
- func (h *SSEHelper) AlertAll(level string, message string)
- func (h *SSEHelper) Notify(clientID string, notification any)
- func (h *SSEHelper) NotifyAll(notification any)
- func (h *SSEHelper) NotifyTopic(topic string, notification any)
- func (h *SSEHelper) Progress(clientID string, progress int, message string)
- func (h *SSEHelper) ProgressTopic(topic string, progress int, message string)
- func (h *SSEHelper) Update(clientID string, key string, value any)
- func (h *SSEHelper) UpdateAll(key string, value any)
- func (h *SSEHelper) UpdateTopic(topic string, key string, value any)
- type SessionStore
- type StackFrame
- type StateLogEntry
- type StaticCompressionMiddleware
- type StreamingCompressionWriter
- type WSClient
- func (c *WSClient) Close()
- func (c *WSClient) ReadPump(hub *WSHub, onMessage func(*WSClient, WSMessage))
- func (c *WSClient) SendError(message string)
- func (c *WSClient) SendInitWithSession(sessionToken string)
- func (c *WSClient) SendJSON(v interface{}) error
- func (c *WSClient) SendState()
- func (c *WSClient) WritePump()
- type WSHub
- type WSMessage
- type WSStateUpdate
- type WebSocketConfig
Constants ¶
This section is empty.
Variables ¶
var ( ErrInternal = NewAppError(ErrorCodeInternal, "Internal server error", fiber.StatusInternalServerError) ErrNotFound = NewAppError(ErrorCodeNotFound, "Resource not found", fiber.StatusNotFound) ErrBadRequest = NewAppError(ErrorCodeBadRequest, "Bad request", fiber.StatusBadRequest) ErrForbidden = NewAppError(ErrorCodeForbidden, "Forbidden", fiber.StatusForbidden) ErrConflict = NewAppError(ErrorCodeConflict, "Conflict", fiber.StatusConflict) ErrValidation = NewAppError(ErrorCodeValidation, "Validation error", fiber.StatusBadRequest) ErrTimeout = NewAppError(ErrorCodeTimeout, "Request timeout", fiber.StatusRequestTimeout) )
Common errors.
Functions ¶
func BroadcastState ¶
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 ¶
CORSMiddleware handles CORS for API routes.
func CSRFTokenMiddleware ¶
CSRFTokenMiddleware provides CSRF protection.
func DebugMiddleware ¶
DebugMiddleware logs requests and state changes.
func DefaultMessageHandler ¶
DefaultMessageHandler handles incoming WebSocket messages.
func ErrorHandler ¶
func ErrorHandler(config ErrorHandlerConfig) fiber.ErrorHandler
ErrorHandler creates a Fiber error handler.
func GetComponentID ¶
GetComponentID extracts the component ID from context.
func GetSessionState ¶
GetSessionState gets or creates session state.
func IsSPANavigation ¶
IsSPANavigation returns true if the current request is an SPA navigation.
func JSONResponse ¶
JSONResponse sends a JSON response.
func PanicHandler ¶
func PanicHandler(config ErrorHandlerConfig) fiber.Handler
PanicHandler creates a panic recovery handler.
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 ¶
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 ¶
RequestLoggerMiddleware logs requests.
func RuntimeMiddleware ¶
RuntimeMiddleware serves the client runtime script. Uses the embedded runtime from the embed package.
func RuntimeMiddlewareWithContent ¶
RuntimeMiddlewareWithContent serves a custom runtime script. This is provided for advanced use cases where a custom runtime is needed.
func SPAMiddleware ¶
SPAMiddleware creates a Fiber middleware for SPA support.
func SPANavigationMiddleware ¶
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 ¶
SecurityHeadersMiddleware adds security headers.
func SendToClient ¶
SendToClient sends a message to a specific client.
func SetSessionState ¶
SetSessionState sets session state.
func StateInspectorMiddleware ¶
StateInspectorMiddleware inspects state changes.
func StateMiddleware ¶
StateMiddleware creates middleware that injects state into responses.
func StateSyncHandler ¶
StateSyncHandler creates a handler for state synchronization.
func WebSocketHandler ¶
func WebSocketHandler(config WebSocketConfig) fiber.Handler
WebSocketHandler creates a WebSocket handler.
func WebSocketUpgradeMiddleware ¶
WebSocketUpgradeMiddleware upgrades HTTP connections to WebSocket.
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 ¶
AsAppError converts an error to AppError.
func NewAppError ¶
NewAppError creates a new application error.
func ValidationError ¶
ValidationError creates a validation error.
func ValidationErrors ¶
ValidationErrors creates a validation error with multiple fields.
func (*AppError) WithDetails ¶
WithDetails adds details to the error.
func (*AppError) WithRecover ¶
WithRecover sets whether state can be recovered.
type ClientStateStore ¶
type ClientStateStore struct {
// contains filtered or unexported fields
}
ClientStateStore persists client state by client ID for session restoration.
func NewClientStateStore ¶
func NewClientStateStore() *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.
type CompressedContent ¶
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.
type ConnectHandler ¶
type ConnectHandler func(client *WSClient)
ConnectHandler is a function that handles a new WebSocket connection.
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 ¶
NewDevTools creates new development tools.
func (*DevTools) DevPanelHandler ¶
DevPanelHandler creates a handler for the dev panel UI.
func (*DevTools) DevToolsHandler ¶
DevToolsHandler creates a WebSocket handler for dev tools.
func (*DevTools) GetStateKeys ¶
GetStateKeys returns all tracked state keys.
func (*DevTools) GetStateLog ¶
func (d *DevTools) GetStateLog() []StateLogEntry
GetStateLog returns the state change log.
func (*DevTools) LogStateChange ¶
LogStateChange logs a state change.
type ErrorCode ¶
type ErrorCode string
ErrorCode represents an error code.
const ( ErrorCodeInternal ErrorCode = "INTERNAL_ERROR" ErrorCodeNotFound ErrorCode = "NOT_FOUND" ErrorCodeBadRequest ErrorCode = "BAD_REQUEST" ErrorCodeForbidden ErrorCode = "FORBIDDEN" ErrorCodeConflict ErrorCode = "CONFLICT" ErrorCodeValidation ErrorCode = "VALIDATION_ERROR" ErrorCodeTimeout ErrorCode = "TIMEOUT" )
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(*fiber.Ctx, *AppError) error
// OnError is called when an error occurs
OnError func(*fiber.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.
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.
type HMRManager ¶
type HMRManager struct {
// contains filtered or unexported fields
}
HMRManager manages hot module replacement.
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.
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() fiber.Handler
HMREndpoint returns a Fiber handler for HMR WebSocket.
func (*HMRManager) HMRMiddleware ¶
func (mgr *HMRManager) HMRMiddleware() fiber.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) 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 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 ¶
NewSSEBroker creates a new SSE broker.
func (*SSEBroker) BroadcastToTopic ¶
BroadcastToTopic sends an event to clients subscribed to a topic.
func (*SSEBroker) ClientCount ¶
ClientCount returns the number of connected clients.
func (*SSEBroker) Disconnect ¶
Disconnect removes an SSE client.
func (*SSEBroker) GetClientsByTopic ¶
GetClientsByTopic returns all clients subscribed to a topic.
func (*SSEBroker) SSEHandler ¶
SSEHandler returns a Fiber handler for SSE connections.
func (*SSEBroker) SSESubscribeHandler ¶
SSESubscribeHandler returns a handler for subscribing to topics. Security: Only allows subscription to topics for clients that are currently connected. This prevents unauthorized clients from subscribing to topics they don't own.
func (*SSEBroker) SSEUnsubscribeHandler ¶
SSEUnsubscribeHandler returns a handler for unsubscribing from topics.
func (*SSEBroker) Unsubscribe ¶
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)
}
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 ¶
NewSSEHelper creates a new SSE helper.
func (*SSEHelper) NotifyTopic ¶
NotifyTopic broadcasts a notification to a topic.
func (*SSEHelper) ProgressTopic ¶
ProgressTopic broadcasts progress 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() *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.
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 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.
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 ¶
NewWSClient creates a new WebSocket client.
func (*WSClient) SendInitWithSession ¶
SendInitWithSession sends the initial state with a session token for HTTP state sync.
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 (*WSHub) BroadcastExcept ¶
BroadcastExcept broadcasts to all clients except the specified one.
func (*WSHub) BroadcastTo ¶
BroadcastTo broadcasts a message to specific clients.
func (*WSHub) ClientCount ¶
ClientCount returns the number of connected clients.
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
}
WebSocketConfig holds WebSocket configuration.
func DefaultWebSocketConfig ¶
func DefaultWebSocketConfig() WebSocketConfig
DefaultWebSocketConfig returns default WebSocket configuration.