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) fiberpkg.Handler
- func DefaultMessageHandler(client *WSClient, msg WSMessage)
- func ErrorHandler(config ErrorHandlerConfig) fiberpkg.ErrorHandler
- func GetComponentID(c gofiber.Ctx, config Config) string
- func GetFlashes(c gofiber.Ctx) map[string]interface{}
- 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()
- func RemoteActionRateLimitMiddleware() fiberpkg.Handler
- func RenderComponent(c gofiber.Ctx, config Config, component templ.Component, componentName string) error
- func RequestLoggerMiddleware() gofiber.Handler
- func RuntimeMiddleware(tier compiler.RuntimeTier) gofiber.Handler
- func RuntimeMiddlewareWithContent(runtimeContent []byte) gofiber.Handler
- func SPAMiddleware(config Config) gofiber.Handler
- func SPANavigationMiddleware() gofiber.Handler
- func SecurityHeadersMiddleware(policy string) gofiber.Handler
- func SendToClient(hub *WSHub, clientID string, message interface{}) error
- func SessionMiddleware() gofiber.Handler
- func SetConnectionRateLimiter(maxTokens float64, refillRate float64)
- func SetFlash(c gofiber.Ctx, key string, value interface{})
- func SetRemoteActionRateLimiter(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(_ *WSHub) fiberpkg.Handler
- func WebSocketHandler(config WebSocketConfig) fiberpkg.Handler
- func WebSocketUpgradeMiddleware() fiberpkg.Handler
- type ActionHandler
- type AppError
- type AtomicRateLimiterStorage
- 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 FileWatcherdeprecated
- 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
- func (s *SessionStore) CreateSession(clientID string) (string, error)
- func (s *SessionStore) GetFlashes(token string) map[string]interface{}
- func (s *SessionStore) RemoveClientSessions(_ string)
- func (s *SessionStore) RemoveSession(token string)
- func (s *SessionStore) SetFlash(token, key string, value interface{}) error
- func (s *SessionStore) ValidateSession(token string) (string, bool)
- type StackFrame
- type StateLogEntry
- type StaticCompressionMiddleware
- type StreamingCompressionWriter
- type WSClient
- func (c *WSClient) Close()
- func (c *WSClient) Marshal(v interface{}) ([]byte, error)
- 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) Unmarshal(data []byte, v interface{}) error
- func (c *WSClient) WritePump()
- type WSHub
- func (h *WSHub) BroadcastExcept(exceptID string, message []byte)
- func (h *WSHub) BroadcastTo(clientIDs []string, message []byte)
- func (h *WSHub) BroadcastToTopic(topic string, message []byte)
- func (h *WSHub) ClientCount() int
- func (h *WSHub) Close()
- func (h *WSHub) GetClient(id string) (*WSClient, bool)
- func (h *WSHub) Run()
- func (h *WSHub) Subscribe(topic string, clientID string)
- func (h *WSHub) Unsubscribe(topic string, clientID string)
- type WSMessage
- type WSStateUpdate
- type WebSocketConfig
Constants ¶
const DefaultContentSecurityPolicy = "" /* 254-byte string literal not displayed */
DefaultContentSecurityPolicy is the default CSP policy for GoSPA. Uses a {nonce} placeholder that SecurityHeadersMiddleware replaces per request.
const LegacyContentSecurityPolicy = "" /* 254-byte string literal not displayed */
LegacyContentSecurityPolicy allows unsafe-inline for script-src. Use only when the application requires inline event handlers or eval-based script execution.
const SessionTTL = 24 * time.Hour
SessionTTL is how long a session token remains valid (default 24 hours).
const StrictContentSecurityPolicy = "" /* 238-byte string literal not displayed */
StrictContentSecurityPolicy is a strict CSP policy that disallows unsafe-inline.
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.
func CSRFSetTokenMiddleware ¶ added in v0.1.3
CSRFSetTokenMiddleware issues and rotates the CSRF cookie on safe HTTP methods.
func CSRFTokenMiddleware ¶
CSRFTokenMiddleware validates CSRF tokens on mutating requests.
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 GetFlashes ¶ added in v0.1.36
GetFlashes retrieves and clears all flash messages from the current session.
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. Link headers are set before downstream handlers run so they arrive in the response headers rather than after the body已经开始解析.
func PreloadHeadersMiddlewareMinimal ¶
func PreloadHeadersMiddlewareMinimal(config PreloadConfig) gofiber.Handler
PreloadHeadersMiddlewareMinimal adds minimal preload headers for micro-runtime.
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) func()
RegisterOnConnectHandler registers a global connect handler. Returns a function to unregister the handler.
func RemoteActionRateLimitMiddleware ¶ added in v0.1.22
RemoteActionRateLimitMiddleware enforces per-IP rate limiting for the HTTP remote action endpoint.
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.
func RuntimeMiddleware ¶
func RuntimeMiddleware(tier compiler.RuntimeTier) gofiber.Handler
RuntimeMiddleware serves the client runtime script. Uses the embedded runtime from the embed package.
func RuntimeMiddlewareWithContent ¶
RuntimeMiddlewareWithContent serves a custom runtime script.
func SPAMiddleware ¶
SPAMiddleware creates a Fiber middleware for SPA support.
func SPANavigationMiddleware ¶
SPANavigationMiddleware detects SPA navigation requests and modifies response.
func SecurityHeadersMiddleware ¶
SecurityHeadersMiddleware adds security headers and handles the CSP nonce.
func SendToClient ¶
SendToClient sends a message to a specific client.
func SessionMiddleware ¶ added in v0.1.32
SessionMiddleware ensures a session token exists in an HttpOnly cookie. This mitigates XSS risks compared to storing tokens in sessionStorage.
func SetConnectionRateLimiter ¶ added in v0.1.6
SetConnectionRateLimiter configures the global connection rate limiter limits.
func SetRemoteActionRateLimiter ¶ added in v0.1.22
SetRemoteActionRateLimiter configures the global remote action 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 enforces per-IP rate limiting before WebSocket upgrade.
Types ¶
type ActionHandler ¶
type ActionHandler func(client *WSClient, payload interface{})
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 AtomicRateLimiterStorage ¶ added in v0.1.29
type AtomicRateLimiterStorage interface {
ConsumeRateLimitToken(ctx context.Context, key string, now time.Time, maxTokens float64, refillRate float64, ttl time.Duration) (bool, error)
}
AtomicRateLimiterStorage allows storage backends to implement atomic distributed rate limiting semantics for shared deployments.
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
// MaxBufferedSize caps the size of responses this middleware will buffer
// and compress in-memory. Larger responses are left untouched so callers
// can use streaming or upstream compression instead.
MaxBufferedSize int
}
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
// EnableWebSocket indicates websocket support is expected by the page bootstrap.
EnableWebSocket bool
// WebSocketPath is the websocket endpoint path.
WebSocketPath string
// ExpectCSPNonce enables startup diagnostics for nonce-based CSP setups.
ExpectCSPNonce bool
// StartupChecks injects runtime self-check diagnostics.
StartupChecks bool
// 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{}
// Logger is the structured logger. Defaults to slog.Default().
Logger *slog.Logger
// BuildManifest is the loaded manifest.json (optional)
BuildManifest map[string]string
}
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) SetLimits ¶ added in v0.1.24
func (rl *ConnectionRateLimiter) SetLimits(maxTokens float64, refillRate float64)
SetLimits configures the burst capacity and refill rate for this specific limiter instance.
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
// AllowInsecureWS allows unsecure ws:// connections
AllowInsecureWS bool
// HMRManager is an optional HMR manager to use for file watching instead of polling
// When set, DevTools will subscribe to HMR file change events instead of using
// the legacy polling FileWatcher. This reduces CPU usage significantly.
HMRManager *HMRManager
}
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 represents an internal server error ErrorCodeInternal ErrorCode = "INTERNAL_ERROR" // ErrorCodeNotFound represents a resource not found error ErrorCodeNotFound ErrorCode = "NOT_FOUND" // ErrorCodeBadRequest represents a bad request error ErrorCodeBadRequest ErrorCode = "BAD_REQUEST" ErrorCodeUnauthorized ErrorCode = "UNAUTHORIZED" // ErrorCodeForbidden represents a forbidden error ErrorCodeForbidden ErrorCode = "FORBIDDEN" // ErrorCodeConflict represents a conflict error ErrorCodeConflict ErrorCode = "CONFLICT" // ErrorCodeValidation represents a validation error ErrorCodeValidation ErrorCode = "VALIDATION_ERROR" // ErrorCodeTimeout represents a timeout 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 ¶
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
deprecated
type FileWatcher struct {
// contains filtered or unexported fields
}
FileWatcher watches for file changes using polling.
Deprecated: This uses CPU-intensive polling (100ms ticker with filepath.Walk). Use HMRManager's HMRFileWatcher instead, which uses efficient fsnotify events. Kept for backwards compatibility when HMR is not available.
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"`
AllowInsecureWS bool `json:"allowInsecureWS"`
}
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"`
}
HMRFileChangeEvent represents a file change event.
type HMRFileWatcher ¶
type HMRFileWatcher struct {
// contains filtered or unexported fields
}
HMRFileWatcher watches files for changes for HMR using fsnotify.
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"`
ReloadReason string `json:"reloadReason,omitempty"` // "template-safe" | "style-safe" | "runtime-break" | "config-break"
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 string
WebSocketScript string
CoreScript string
MicroScript string
// CSSLinks contains stylesheets to preload with high priority
CSSLinks []string
Enabled bool
// BuildManifest is the loaded manifest.json (optional)
BuildManifest map[string]string
}
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
// AuthorizeSubscribe is called to authorize a subscription request.
// It should return true if the requester (c) is authorized to subscribe the client (clientID).
AuthorizeSubscribe func(c fiberpkg.Ctx, clientID string) bool
}
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, error)
CreateSession creates a new session token for a client ID. Returns the session token and an error if token generation or persistence fails.
func (*SessionStore) GetFlashes ¶ added in v0.1.36
func (s *SessionStore) GetFlashes(token string) map[string]interface{}
GetFlashes retrieves and removes all flash messages for a session.
func (*SessionStore) RemoveClientSessions ¶
func (s *SessionStore) RemoveClientSessions(_ 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) SetFlash ¶ added in v0.1.36
func (s *SessionStore) SetFlash(token, key string, value interface{}) error
SetFlash sets a flash message for a session.
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, _ 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 ¶
func NewWSClient(id string, conn *websocket.Conn, config WebSocketConfig) *WSClient
NewWSClient creates a new WebSocket client.
func (*WSClient) Marshal ¶ added in v0.1.24
Marshal marshals a value using the client's configured format.
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
ClientsBySession map[string]map[string]*WSClient // SessionID -> {ClientID -> *WSClient}
ClientsByTopic map[string]map[string]*WSClient // Topic -> {ClientID -> *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) BroadcastToTopic ¶ added in v0.1.36
BroadcastToTopic sends a message to all clients subscribed to a topic.
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. It is safe to call Close multiple times.
func (*WSHub) Unsubscribe ¶ added in v0.1.36
Unsubscribe removes a client from a topic.
type WSMessage ¶
type WSMessage struct {
Type string `json:"type" msgpack:"type"`
ComponentID string `json:"componentId,omitempty" msgpack:"componentId,omitempty"`
Action string `json:"action,omitempty" msgpack:"action,omitempty"`
Data map[string]interface{} `json:"data,omitempty" msgpack:"data,omitempty"`
Payload interface{} `json:"payload,omitempty" msgpack:"payload,omitempty"`
SessionToken string `json:"sessionToken,omitempty" msgpack:"sessionToken,omitempty"`
ClientID string `json:"clientId,omitempty" msgpack:"clientId,omitempty"`
}
WSMessage represents a WebSocket message.
type WSStateUpdate ¶
type WSStateUpdate struct {
Key string `json:"key" msgpack:"key"`
Value interface{} `json:"value" msgpack:"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
// SerializationFormat sets the underlying format for all WebSocket communications.
SerializationFormat string
// 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.