gospa

package module
v0.1.29 Latest Latest
Warning

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

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

README

GoSPA

GoSPA Logo 1 GoSPA Logo 2

GoSPA brings Svelte-like reactive primitives (Runes, Effects, Derived) to the Go ecosystem. It is a high-performance framework for building reactive SPAs with Templ, Fiber, file-based routing, and real-time state synchronization.

Highlights

  • Native Reactivity - Rune, Derived, Effect primitives that work exactly like Svelte 5.
  • WebSocket Sync - Transparent client-server state synchronization with GZIP delta patching.
  • File-Based Routing - SvelteKit-style directory structure for .templ files.
  • Hybrid Rendering - Mix SSR, SSG, ISR, and PPR on a per-page basis.
  • Type-Safe RPC - Call server functions directly from the client without boilerplate endpoints.
  • High Performance - Integrated go-json and optional MessagePack for minimal overhead.

Quick Start

1. Install CLI
go install github.com/aydenstechdungeon/gospa/cmd/gospa@latest
2. Scaffold & Run
gospa create myapp
cd myapp
go mod tidy
gospa dev
3. A Simple Page
// routes/page.templ
package routes

templ Page() {
    <div data-gospa-component="counter" data-gospa-state='{"count":0}'>
        <h1 data-bind="text:count">0</h1>
        <button data-on="click:increment">+</button>
    </div>
}

Comparison

Feature GoSPA HTMX Alpine SvelteKit
Language Go HTML JS JS/TS
Runtime ~15KB ~14KB ~15KB Varies
Reactivity
WS Sync
File Routing
Type Safety

Documentation

Full guides and API reference are available at gospa.onrender.com or in the /docs directory.


Apache License 2.0

Documentation

Overview

Package gospa provides a modern SPA framework for Go with Fiber and Templ. It brings Svelte-like reactivity and state management to Go.

Index

Constants

View Source
const (
	SerializationJSON    = "json"
	SerializationMsgPack = "msgpack"
)

Serialization formats

View Source
const Version = "0.1.29"

Version is the current version of GoSPA.

Variables

This section is empty.

Functions

This section is empty.

Types

type App

type App struct {
	// Config is the application configuration.
	Config Config
	// Router is the file-based router.
	Router *routing.Router
	// Fiber is the underlying Fiber app.
	Fiber *fiberpkg.App
	// Hub is the WebSocket hub for real-time updates.
	Hub *fiber.WSHub
	// StateMap is the global state map.
	StateMap *state.StateMap
	// contains filtered or unexported fields
}

App is the main GoSPA application.

func New

func New(config Config) *App

New creates a new GoSPA application.

func (*App) Broadcast

func (a *App) Broadcast(message []byte)

Broadcast sends a message to all connected WebSocket clients.

func (*App) BroadcastState

func (a *App) BroadcastState(key string, value interface{}) error

BroadcastState broadcasts a state update to all connected WebSocket clients.

func (*App) Delete

func (a *App) Delete(path string, handlers ...fiberpkg.Handler)

Delete adds a DELETE route.

func (*App) Get

func (a *App) Get(path string, handlers ...fiberpkg.Handler)

Get adds a GET route.

func (*App) GetFiber

func (a *App) GetFiber() *fiberpkg.App

GetFiber returns the underlying Fiber app.

func (*App) GetHub

func (a *App) GetHub() *fiber.WSHub

GetHub returns the WebSocket hub.

func (*App) GetPlugin added in v0.1.29

func (a *App) GetPlugin(name string) (plugin.Plugin, bool)

GetPlugin returns a registered plugin by name.

func (*App) GetRouter

func (a *App) GetRouter() *routing.Router

GetRouter returns the file-based router.

func (*App) GetTemplateFuncs added in v0.1.29

func (a *App) GetTemplateFuncs() map[string]any

GetTemplateFuncs returns all plugin template functions.

func (*App) Group

func (a *App) Group(prefix string, handlers ...fiberpkg.Handler) fiberpkg.Router

Group creates a route group.

func (*App) ListPlugins added in v0.1.29

func (a *App) ListPlugins() []plugin.Info

ListPlugins returns all registered plugins.

func (*App) Logger added in v0.1.24

func (a *App) Logger() *slog.Logger

Logger returns the configured logger.

func (*App) Post

func (a *App) Post(path string, handlers ...fiberpkg.Handler)

Post adds a POST route.

func (*App) Put

func (a *App) Put(path string, handlers ...fiberpkg.Handler)

Put adds a PUT route.

func (*App) RegisterRoutes

func (a *App) RegisterRoutes() error

RegisterRoutes registers all scanned routes with Fiber.

func (*App) Run

func (a *App) Run(addr string) error

Run starts the application on the given address.

func (*App) RunTLS

func (a *App) RunTLS(addr, certFile, keyFile string) error

RunTLS starts the application with TLS on the given address.

func (*App) Scan

func (a *App) Scan() error

Scan scans the routes directory and builds the route tree.

func (*App) Shutdown

func (a *App) Shutdown() error

Shutdown gracefully shuts down the application.

func (*App) Static

func (a *App) Static(prefix, root string)

Static serves static files via the static middleware.

func (*App) Use

func (a *App) Use(middleware ...fiberpkg.Handler)

Use adds a middleware to the application.

func (*App) UsePlugin added in v0.1.29

func (a *App) UsePlugin(p plugin.Plugin) error

UsePlugin registers a plugin with the application.

func (*App) UsePlugins added in v0.1.29

func (a *App) UsePlugins(plugins ...plugin.Plugin) error

UsePlugins registers multiple plugins with the application.

type Config

type Config struct {
	// RoutesDir is the directory containing route files.
	RoutesDir string
	// RoutesFS is the filesystem containing route files (optional). Takes precedence over RoutesDir if provided.
	RoutesFS fs.FS
	// DevMode enables development features.
	DevMode bool
	// RuntimeScript is the path to the client runtime script.
	RuntimeScript string
	// StaticDir is the directory for static files.
	StaticDir string
	// StaticPrefix is the URL prefix for static files.
	StaticPrefix string
	// AppName is the application name.
	AppName string
	// DefaultState is the initial state for new sessions.
	DefaultState map[string]interface{}
	// EnableWebSocket enables WebSocket support.
	EnableWebSocket bool
	// WebSocketPath is the WebSocket endpoint path.
	WebSocketPath string
	// WebSocketMiddleware allows injecting session/auth middleware before WebSocket upgrade.
	WebSocketMiddleware fiberpkg.Handler
	// Logger is the structured logger. Defaults to slog.Default().
	Logger *slog.Logger

	// Performance Options
	// CompressState enables gzip compression of outbound WebSocket state payloads.
	// The client receives a { type:"compressed", data: "<base64>", compressed: true }
	// envelope and must decompress using the DecompressionStream browser API.
	CompressState bool
	// StateDiffing enables delta-only "patch" WebSocket messages for state syncs.
	// Only changed state keys are transmitted after the initial full snapshot.
	StateDiffing   bool
	CacheTemplates bool // Cache compiled templates (SSG only)
	SimpleRuntime  bool // Use lightweight runtime without DOMPurify (~6KB smaller)
	// SimpleRuntimeSVGs allows SVG elements in the simple runtime sanitizer.
	// WARNING: Only enable if your content is fully trusted and never user-generated.
	SimpleRuntimeSVGs bool
	// DisableSanitization disables client-side HTML sanitization for SPA navigation.
	// When enabled, GoSPA trusts server-rendered HTML without DOMPurify filtering.
	// This provides a SvelteKit-like experience but requires careful handling of
	// user-generated content. Use with caution - only for trusted content.
	DisableSanitization bool

	// WebSocket Options — these values are passed directly to the client runtime's init() call.
	// Defaults: WSReconnectDelay=1s, WSMaxReconnect=10, WSHeartbeat=30s.
	WSReconnectDelay time.Duration // Initial reconnect delay (default 1s)
	WSMaxReconnect   int           // Max reconnect attempts (default 10)
	WSHeartbeat      time.Duration // Heartbeat ping interval (default 30s)

	// WSMaxMessageSize limits the maximum payload size for WebSocket messages (default 64KB).
	WSMaxMessageSize int
	// WSConnRateLimit sets the refilling rate in connections per second for WebSocket upgrades (default 1.5).
	WSConnRateLimit float64
	// WSConnBurst sets the burst capacity for WebSocket connection upgrades (default 15.0).
	WSConnBurst float64

	// Hydration Options
	// HydrationMode controls when components become interactive.
	// Supported values: "immediate" | "lazy" | "visible" | "idle" (default: "immediate").
	HydrationMode    string
	HydrationTimeout int // ms before force hydrate (used with "visible" and "idle" modes)

	// Serialization Options
	// SerializationFormat sets the underlying format for all WebSocket communications.
	// Supported values: "json" (default, using goccy/go-json) | "msgpack".
	SerializationFormat string
	// StateSerializer overrides the default state serialization for outbound WebSocket payloads.
	// StateDeserializer overrides the default state deserialization for inbound WebSocket payloads.
	StateSerializer   StateSerializerFunc
	StateDeserializer StateDeserializerFunc

	// Routing Options
	DisableSPA bool // Disable SPA navigation completely

	// Rendering Strategy Defaults
	// DefaultRenderStrategy sets the fallback strategy for pages that do not
	// explicitly call RegisterPageWithOptions. Defaults to StrategySSR.
	DefaultRenderStrategy routing.RenderStrategy
	// DefaultRevalidateAfter is the ISR TTL used when a page uses StrategyISR
	// but does not set RouteOptions.RevalidateAfter. Zero means revalidate every request.
	DefaultRevalidateAfter time.Duration

	// Remote Action Options
	MaxRequestBodySize int    // Maximum allowed size for remote action request bodies
	RemotePrefix       string // Prefix for remote action endpoints (default "/_gospa/remote")
	// RemoteActionMiddleware allows injecting authorization/tenant checks before remote action handlers.
	RemoteActionMiddleware fiberpkg.Handler
	// AllowUnauthenticatedRemoteActions disables the production safety guard that blocks
	// remote actions when no RemoteActionMiddleware is configured.
	// Default false (secure-by-default).
	AllowUnauthenticatedRemoteActions bool

	// Security Options
	AllowedOrigins        []string // Allowed CORS origins
	EnableCSRF            bool     // Enable automatic CSRF protection (requires CSRFSetTokenMiddleware + CSRFTokenMiddleware)
	ContentSecurityPolicy string   // Optional CSP header. Empty uses the secure default policy.
	// SSGCacheMaxEntries caps the SSG/ISR/PPR page cache size. Oldest entries are evicted when full.
	// Default: 500. Set to -1 to disable eviction (unbounded, not recommended in production).
	SSGCacheMaxEntries int
	// SSGCacheTTL sets an expiration time for SSG cache entries. If zero, they never expire.
	SSGCacheTTL time.Duration

	// Prefork enables Fiber's prefork mode.
	// WARNING: If enabled without an external Storage/PubSub backend like Redis, in-memory state and WebSockets will be isolated per-process.
	Prefork bool

	// Storage defines the external storage backend for sessions and state. Defaults to in-memory.
	Storage store.Storage

	// PubSub defines the messaging backend for multi-process broadcasting. Defaults to in-memory.
	PubSub store.PubSub

	// NavigationOptions configures optional client-side navigation behavior and performance optimizations.
	NavigationOptions NavigationOptions
}

Config holds the application configuration.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns the default configuration.

type NavigationIdleCallbackBatchUpdatesConfig struct {
	Enabled             *bool `json:"enabled,omitempty"`
	FallbackToMicrotask *bool `json:"fallbackToMicrotask,omitempty"`
}

NavigationIdleCallbackBatchUpdatesConfig configures idle callback batching

type NavigationLazyRuntimeInitializationConfig struct {
	Enabled       *bool `json:"enabled,omitempty"`
	DeferBindings *bool `json:"deferBindings,omitempty"`
}

NavigationLazyRuntimeInitializationConfig configures lazy runtime init

type NavigationOptions struct {
	SpeculativePrefetching         *NavigationSpeculativePrefetchingConfig    `json:"speculativePrefetching,omitempty"`
	URLParsingCache                *NavigationURLParsingCacheConfig           `json:"urlParsingCache,omitempty"`
	IdleCallbackBatchUpdates       *NavigationIdleCallbackBatchUpdatesConfig  `json:"idleCallbackBatchUpdates,omitempty"`
	LazyRuntimeInitialization      *NavigationLazyRuntimeInitializationConfig `json:"lazyRuntimeInitialization,omitempty"`
	ServiceWorkerNavigationCaching *NavigationServiceWorkerCachingConfig      `json:"serviceWorkerNavigationCaching,omitempty"`
	ViewTransitions                *NavigationViewTransitionsConfig           `json:"viewTransitions,omitempty"`
}

NavigationOptions configures client-side navigation

type NavigationServiceWorkerCachingConfig struct {
	Enabled   *bool  `json:"enabled,omitempty"`
	CacheName string `json:"cacheName,omitempty"`
	Path      string `json:"path,omitempty"`
}

NavigationServiceWorkerCachingConfig configures service worker caching

type NavigationSpeculativePrefetchingConfig struct {
	Enabled        *bool `json:"enabled,omitempty"`
	TTL            *int  `json:"ttl,omitempty"`
	HoverDelay     *int  `json:"hoverDelay,omitempty"`
	ViewportMargin *int  `json:"viewportMargin,omitempty"`
}

NavigationSpeculativePrefetchingConfig configures speculative prefetching

type NavigationURLParsingCacheConfig struct {
	Enabled *bool `json:"enabled,omitempty"`
	MaxSize *int  `json:"maxSize,omitempty"`
	TTL     *int  `json:"ttl,omitempty"`
}

NavigationURLParsingCacheConfig configures the URL parsing cache

type NavigationViewTransitionsConfig struct {
	Enabled           *bool `json:"enabled,omitempty"`
	FallbackToClassic *bool `json:"fallbackToClassic,omitempty"`
}

NavigationViewTransitionsConfig configures view transitions

type StateDeserializerFunc

type StateDeserializerFunc func([]byte, interface{}) error

StateDeserializerFunc defines a function for state deserialization

type StateSerializerFunc

type StateSerializerFunc func(interface{}) ([]byte, error)

StateSerializerFunc defines a function for state serialization

Directories

Path Synopsis
Package cli provides command-line interface tools for GoSPA.
Package cli provides command-line interface tools for GoSPA.
cmd
gospa command
gospa-gen command
Package main provides a code generator for GoSPA route registration.
Package main provides a code generator for GoSPA route registration.
Package component provides island architecture support for GoSPA.
Package component provides island architecture support for GoSPA.
starter
Package starter provides a library of reusable UI components for GoSPA applications
Package starter provides a library of reusable UI components for GoSPA applications
Package embed provides embedded static assets for the GoSPA framework.
Package embed provides embedded static assets for the GoSPA framework.
examples
form-remote module
Package fiber provides error overlay functionality for development.
Package fiber provides error overlay functionality for development.
Package plugin provides external plugin loading capabilities for GoSPA.
Package plugin provides external plugin loading capabilities for GoSPA.
auth
Package auth provides authentication for GoSPA projects.
Package auth provides authentication for GoSPA projects.
image
Package image provides image optimization for GoSPA projects.
Package image provides image optimization for GoSPA projects.
postcss
Package postcss provides a PostCSS plugin for GoSPA with Tailwind CSS v4 support.
Package postcss provides a PostCSS plugin for GoSPA with Tailwind CSS v4 support.
qrcode
Package qrcode provides QR code generation for GoSPA applications.
Package qrcode provides QR code generation for GoSPA applications.
seo
Package seo provides SEO optimization for GoSPA projects.
Package seo provides SEO optimization for GoSPA projects.
tailwind
Package tailwind provides a Tailwind CSS v4 plugin for GoSPA.
Package tailwind provides a Tailwind CSS v4 plugin for GoSPA.
validation
Package validation provides form validation for GoSPA projects.
Package validation provides form validation for GoSPA projects.
Package routing provides file-based routing similar to SvelteKit.
Package routing provides file-based routing similar to SvelteKit.
generator
Package generator provides code generation for automatic route registration.
Package generator provides code generation for automatic route registration.
Package main is a script to bump version and create a new git tag.
Package main is a script to bump version and create a new git tag.
Package state provides batch update support for reactive primitives.
Package state provides batch update support for reactive primitives.
Package store provides pubsub state backends for GoSPA.
Package store provides pubsub state backends for GoSPA.
redis
Package redis provides a Redis-backed implementation of the store.Storage interface.
Package redis provides a Redis-backed implementation of the store.Storage interface.
Package templ provides Templ integration helpers for GoSPA reactive bindings.
Package templ provides Templ integration helpers for GoSPA reactive bindings.
Package main is the benchmark tool for GoSPA.
Package main is the benchmark tool for GoSPA.
website module

Jump to

Keyboard shortcuts

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