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
- Variables
- func BroadcastState(hub *WSHub, key string, value interface{}) error
- func BrotliGzipMiddleware(config CompressionConfig) gofiber.Handler
- func CORSMiddleware(allowedOrigins []string) gofiber.Handler
- func CSRFSetTokenMiddleware() gofiber.Handler
- func CSRFTokenMiddleware() gofiber.Handler
- func DebugMiddleware(devTools *DevTools) fiberpkg.Handler
- func DefaultMessageHandler(client *WSClient, msg WSMessage)
- func ErrorHandler(config ErrorHandlerConfig) fiberpkg.ErrorHandler
- func GetComponentID(c *gofiber.Ctx, config Config) string
- func GetIPFromContext(c *fiberpkg.Ctx) string
- func GetSessionState(c *gofiber.Ctx, config Config) map[string]interface{}
- func GetState(c *gofiber.Ctx, config Config) *state.StateMap
- func InitStores(storage store.Storage)
- 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() fiberpkg.Handler
- func PanicHandler(config ErrorHandlerConfig) fiberpkg.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 SetConnectionRateLimiter(maxTokens float64, refillRate float64)
- func SetSessionState(c *gofiber.Ctx, config Config, key string, value interface{})
- func SetupSSE(app *fiberpkg.App, broker *SSEBroker, basePath string, corsConfig *cors.Config)
- func StateInspectorMiddleware(devTools *DevTools, config Config) fiberpkg.Handler
- func StateMiddleware(config Config) gofiber.Handler
- func StateSyncHandler(hub *WSHub) fiberpkg.Handler
- func WebSocketHandler(config WebSocketConfig) fiberpkg.Handler
- func WebSocketUpgradeMiddleware() fiberpkg.Handler
- type ActionHandler
- type AppError
- type ClientStateStore
- type CompressedContent
- type CompressionConfig
- type Config
- type ConnectHandler
- type ConnectionRateLimiter
- type DevConfig
- type DevTools
- func (d *DevTools) DevPanelHandler() fiberpkg.Handler
- func (d *DevTools) DevToolsHandler() fiberpkg.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() fiberpkg.Handler
- func (mgr *HMRManager) HMRMiddleware() fiberpkg.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(*fiberpkg.Ctx) string) fiberpkg.Handler
- func (b *SSEBroker) SSESubscribeHandler() fiberpkg.Handler
- func (b *SSEBroker) SSEUnsubscribeHandler() fiberpkg.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 ¶
const SessionTTL = 24 * time.Hour
SessionTTL is how long a session token remains valid (default 24 hours).
Variables ¶
var ( ErrInternal = NewAppError(ErrorCodeInternal, "Internal server error", fiberpkg.StatusInternalServerError) ErrNotFound = NewAppError(ErrorCodeNotFound, "Resource not found", fiberpkg.StatusNotFound) ErrBadRequest = NewAppError(ErrorCodeBadRequest, "Bad request", fiberpkg.StatusBadRequest) 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) )
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. 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
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 ¶
CSRFTokenMiddleware validates CSRF tokens on mutating requests. IMPORTANT: Use CSRFSetTokenMiddleware() as well so the token is actually issued.
func DebugMiddleware ¶
DebugMiddleware logs requests and state changes.
func DefaultMessageHandler ¶
DefaultMessageHandler handles incoming WebSocket messages.
func ErrorHandler ¶
func ErrorHandler(config ErrorHandlerConfig) fiberpkg.ErrorHandler
ErrorHandler creates a Fiber error handler.
func GetComponentID ¶
GetComponentID extracts the component ID from context.
func GetIPFromContext ¶ added in v0.1.5
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 ¶
GetSessionState gets or creates session state.
func InitStores ¶ added in v0.1.4
InitStores updates the global stores to use the provided storage backend.
func IsSPANavigation ¶
IsSPANavigation returns true if the current request is an SPA navigation.
func JSONResponse ¶
JSONResponse sends a JSON response.
func NotFoundHandler ¶
NotFoundHandler creates a 404 handler.
func PanicHandler ¶
func PanicHandler(config ErrorHandlerConfig) fiberpkg.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 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 ¶
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 SetConnectionRateLimiter ¶ added in v0.1.6
SetConnectionRateLimiter configures the global connection rate limiter limits.
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) 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 ¶
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 ¶
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(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.
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 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 ¶
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(*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.
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. 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) 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 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 ¶
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)
// 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 ¶
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(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.
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.
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.
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.
func (*WSHub) Close ¶ added in v0.1.13
func (h *WSHub) Close()
Close explicitly stops the WSHub 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.