Documentation
¶
Overview ¶
Package vango provides the public API for the Vango web framework.
This is the recommended import for most applications:
import "github.com/vango-go/vango"
Usage:
return vango.Setup(vango.NoProps{}, func(s vango.SetupCtx[vango.NoProps]) vango.RenderFn {
count := setup.Signal(&s, 0)
form := setup.Form(&s, MyFormData{})
search := setup.URLParam(&s, "q", "", vango.Replace, vango.URLDebounce(300*time.Millisecond))
return func() *vango.VNode {
_ = count
_ = form
_ = search
return Div()
}
})
Index ¶
- Constants
- Variables
- func Async(fn func(value any) (error, bool)) *form.AsyncValidator
- func DecodeHookPayload[T any](event HookEvent) (T, error)
- func DecodeIslandPayload[T any](msg IslandMessage) (T, error)
- func DecodeWasmPayload[T any](msg WasmMessage) (T, error)
- func DisableGlobalSignalRefresh() *time.Duration
- func EqualTo(field string, msg string) *form.EqualToField
- func Func(render func() *vdom.VNode) vdom.Component
- func GlobalSignalRefreshInterval(d time.Duration) *time.Duration
- func Hook(name string, config any) vdom.Attr
- func InSessionLoop() bool
- func NoResume() *time.Duration
- func NotEqualTo(field string, msg string) *form.NotEqualToField
- func OnEvent(name string, handler func(HookEvent)) vdom.Attr
- func OnEventValidated(name string, validate HookEventValidator, handler func(HookEvent)) vdom.Attr
- func ParseForm(r *http.Request, dst any) error
- func ParseFormData(fd FormData, dst any) error
- func ParseFormWithLimit(r *http.Request, dst any, maxBytes int64) error
- func ResumeWindow(d time.Duration) *time.Duration
- func Setup[P any](p P, fn func(corevango.SetupCtx[P]) corevango.RenderFn) corevango.Component
- func UntrackedGet[T any](s *Signal[T]) T
- func UserFromContext(ctx context.Context) any
- func UserFromContextAs[T any](ctx context.Context) (T, bool)
- func WithUser(ctx context.Context, user any) context.Context
- type APIConfig
- type APIHandler
- type Action
- type ActionCtx
- type ActionHandler
- type ActionOption
- type ActionRejection
- type ActionRejectionReason
- type ActionState
- type AnimationEvent
- type App
- func (a *App) API(method, path string, handler APIHandler)
- func (a *App) Config() Config
- func (a *App) HandleUpload(path string, store upload.Store)
- func (a *App) HandleUploadWithConfig(path string, store upload.Store, config *upload.Config)
- func (a *App) Handler() http.Handler
- func (a *App) Layout(path string, handler LayoutHandler)
- func (a *App) Middleware(path string, mw ...RouteMiddleware)
- func (a *App) Page(path string, handler PageHandler, layouts ...LayoutHandler)
- func (a *App) PageAction(path string, handler any)
- func (a *App) Router() *router.Router
- func (a *App) Run(ctx context.Context, addr string) error
- func (a *App) RunAddr(addr string) error
- func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (a *App) Server() *server.Server
- func (a *App) SetErrorPage(handler func(Ctx, error) *VNode)
- func (a *App) SetNotFound(handler PageHandler)
- func (a *App) UnsafeConfigReport() server.UnsafeConfigReport
- func (a *App) Use(mw ...RouteMiddleware)
- type AssetManifest
- type AssetResolver
- type Attr
- type AuthCheckConfig
- type AuthExpiredAction
- type AuthExpiredConfig
- type AuthExpiredReason
- type AuthFailureMode
- type AuthResumePolicy
- type CacheControlStrategy
- type Cleanup
- type Component
- type Config
- type CookieOption
- type Ctx
- type DragEvent
- type DropEvent
- type EventRateLimitConfig
- type Form
- type FormData
- type FormErrors
- type FormResult
- type GlobalBroadcastBackend
- type HTTPError
- type Handler
- type HookEvent
- type HookEventValidator
- type HostedSurfaceSecurityConfig
- type InputEvent
- type IslandMessage
- type IslandMessageValidator
- type KeyMod
- type KeyboardEvent
- type LayoutHandler
- type Memo
- type MetricsSink
- type ModifiedHandler
- func Capture(handler any) ModifiedHandler
- func Debounce(duration time.Duration, handler any) ModifiedHandler
- func Hotkey(key string, handler any) ModifiedHandler
- func KeyWithModifiers(key string, mods KeyMod, handler any) ModifiedHandler
- func Keys(keys []string, handler any) ModifiedHandler
- func Once(handler any) ModifiedHandler
- func Passive(handler any) ModifiedHandler
- func PreventDefault(handler any) ModifiedHandler
- func Self(handler any) ModifiedHandler
- func StopPropagation(handler any) ModifiedHandler
- func Throttle(duration time.Duration, handler any) ModifiedHandler
- type MouseEvent
- type NavigateEvent
- type NavigateOption
- type NoProps
- type ObservabilityConfig
- type PageHandler
- type PagedResponse
- type Principal
- type Props
- type PropsCell
- type RenderFn
- type ResizeEvent
- type Resource
- type ResourceOption
- type ResourceState
- type Response
- type RouteMiddleware
- type RouteMiddlewareFunc
- type RuntimeUnsafePermissions
- type SSRConfig
- type ScriptsOption
- func WithAllowInsecureModuleOrigins() ScriptsOption
- func WithAllowInsecureModuleOriginsAcknowledged(token string) ScriptsOption
- func WithAllowSrcdoc() ScriptsOption
- func WithAllowUnsafeRawHTML() ScriptsOption
- func WithAllowUnsafeRawHTMLAcknowledged(token string) ScriptsOption
- func WithCSRFToken(token string) ScriptsOption
- func WithDebug() ScriptsOption
- func WithModuleOrigins(origins ...string) ScriptsOption
- func WithRuntimeUnsafePermissions(perms RuntimeUnsafePermissions) ScriptsOption
- func WithScriptPath(path string) ScriptsOption
- func WithoutDefer() ScriptsOption
- type ScrollEvent
- type SecurityConfig
- type SecurityHeadersConfig
- type Session
- type SessionConfig
- type SessionEvictionPolicy
- type SessionKey
- type SessionKeyOption
- type SessionStore
- type SetupCtx
- type Signal
- type Slot
- type StateBudgetConfig
- type StaticConfig
- type StormBudgetConfig
- type Touch
- type TouchEvent
- type TransitionEvent
- type URLEncoding
- type URLParamOption
- type URLPolicyConfig
- type UnsafeConfigCode
- type UnsafeConfigEntry
- type UnsafeConfigReport
- type UnsafeConfigSeverity
- type UnsafeConfigState
- type VKind
- type VNode
- type ValidationError
- type Validator
- func Alpha(msg string) Validator
- func AlphaNumeric(msg string) Validator
- func Between(min, max any, msg string) Validator
- func Custom(fn func(value any) error) Validator
- func DateAfter(t time.Time, msg string) Validator
- func DateBefore(t time.Time, msg string) Validator
- func Email(msg string) Validator
- func Future(msg string) Validator
- func Max(n any, msg string) Validator
- func MaxLength(n int, msg string) Validator
- func Min(n any, msg string) Validator
- func MinLength(n int, msg string) Validator
- func NonNegative(msg string) Validator
- func Numeric(msg string) Validator
- func Past(msg string) Validator
- func Pattern(pattern, msg string) Validator
- func Phone(msg string) Validator
- func Positive(msg string) Validator
- func Required(msg string) Validator
- func URL(msg string) Validator
- func UUID(msg string) Validator
- type ValidatorFunc
- type WasmMessage
- type WasmMessageValidator
- type WheelEvent
Constants ¶
const ( // EvictionLRU evicts the least recently accessed detached sessions first. EvictionLRU = server.EvictionLRU // EvictionOldest evicts the oldest sessions first (by creation time). EvictionOldest = server.EvictionOldest // EvictionRandom evicts sessions randomly (faster but less fair). EvictionRandom = server.EvictionRandom )
const ( // Failure modes FailOpenWithGrace = server.FailOpenWithGrace FailClosed = server.FailClosed // Expiry actions ForceReload = server.ForceReload AuthCustom = server.Custom // Expiry reasons AuthExpiredUnknown = server.AuthExpiredUnknown AuthExpiredPassiveExpiry = server.AuthExpiredPassiveExpiry AuthExpiredResumeRehydrateFailed = server.AuthExpiredResumeRehydrateFailed AuthExpiredActiveRevalidateFailed = server.AuthExpiredActiveRevalidateFailed AuthExpiredOnDemandRevalidateFailed = server.AuthExpiredOnDemandRevalidateFailed AuthExpiredNoRevalidationHooks = server.AuthExpiredNoRevalidationHooks // Auth resume policies AuthResumePolicyStrict = server.AuthResumePolicyStrict AuthResumePolicyTrustSessionID = server.AuthResumePolicyTrustSessionID UnsafeConfigCodeDevMode = server.UnsafeConfigCodeDevMode UnsafeConfigCodeTrustSessionID = server.UnsafeConfigCodeTrustSessionID UnsafeConfigCodeUnsafeRawHTML = server.UnsafeConfigCodeUnsafeRawHTML UnsafeConfigCodeInsecureModuleOrigins = server.UnsafeConfigCodeInsecureModuleOrigins UnsafeConfigCodeHeuristicEventPayloads = server.UnsafeConfigCodeHeuristicEventPayloads UnsafeConfigStateActive = server.UnsafeConfigStateActive UnsafeConfigStatePermission = server.UnsafeConfigStatePermission UnsafeConfigSeverityCritical = server.UnsafeConfigSeverityCritical UnsafeConfigSeverityHigh = server.UnsafeConfigSeverityHigh UnsafeConfigSeverityModerate = server.UnsafeConfigSeverityModerate DevModeRiskAcceptanceV1 = server.DevModeRiskAcceptanceV1 TrustSessionIDRiskAcceptanceV1 = server.TrustSessionIDRiskAcceptanceV1 UnsafeRawHTMLRiskAcceptanceV1 = server.UnsafeRawHTMLRiskAcceptanceV1 InsecureModuleOriginsRiskAcceptanceV1 = server.InsecureModuleOriginsRiskAcceptanceV1 HeuristicEventPayloadRiskAcceptanceV1 = server.HeuristicEventPayloadRiskAcceptanceV1 )
const ( // HostedSurfaceProofSecretEnv is the environment variable read by hosted // macOS native hosts and app servers for signed surface proof verification. HostedSurfaceProofSecretEnv = envHostedSurfaceProofSecret // HostedSurfaceTokenSecretEnv is the server-only environment variable used // to sign hosted auth bootstrap tokens. HostedSurfaceTokenSecretEnv = envHostedSurfaceTokenSecret // HostedSurfaceAllowedOriginsEnv lists comma-separated trusted hosted origins. HostedSurfaceAllowedOriginsEnv = envHostedSurfaceOrigins )
const ( ActionRejectQueueFull = corevango.ActionRejectQueueFull ActionRejectDropWhileRunning = corevango.ActionRejectDropWhileRunning )
const ( Ctrl = corevango.Ctrl Shift = corevango.Shift Alt = corevango.Alt Meta = corevango.Meta )
const ( ActionIdle = corevango.ActionIdle ActionRunning = corevango.ActionRunning ActionSuccess = corevango.ActionSuccess ActionError = corevango.ActionError )
ActionState constants
const ( KindElement = vdom.KindElement KindText = vdom.KindText KindFragment = vdom.KindFragment KindComponent = vdom.KindComponent KindRaw = vdom.KindRaw )
VKind constants
const DefaultFormMaxBytes int64 = 1 << 20
DefaultFormMaxBytes is the default maximum size for form bodies parsed by ParseForm. 1 MiB is a safe baseline for typical form submissions.
Variables ¶
var ActionOnError = corevango.ActionOnError
var ActionOnStart = corevango.OnActionStart
var ActionOnSuccess = corevango.ActionOnSuccess
var ActionTxName = corevango.ActionTxName
var BadRequest = corevango.BadRequest
var BadRequestf = corevango.BadRequestf
var Batch = corevango.Batch
Batch groups multiple signal updates into a single notification.
var CSRFCtxToken = server.CSRFCtxToken
var CancelLatest = corevango.CancelLatest
var Conflict = corevango.Conflict
var DevMode = &corevango.DevMode
DevMode enables development-time validation. When true, write violations panic with descriptive messages. When false (production), invalid writes are logged and dropped. DevMode is automatically enabled for test binaries.
var DropWhileRunning = corevango.DropWhileRunning
var ErrActionRunning = corevango.ErrActionRunning
var ErrAuthCheckPanicked = server.ErrAuthCheckPanicked
var ErrBudgetExceeded = corevango.ErrBudgetExceeded
var ErrQueueFull = corevango.ErrQueueFull
var Forbidden = corevango.Forbidden
var InternalError = corevango.InternalError
var Interval = corevango.Interval
var Invalid = corevango.Invalid
var NotFound = corevango.NotFound
var OnActionRejected = corevango.OnActionRejected
var Queue = corevango.Queue
var RedirectTo = corevango.RedirectTo
var StrictConcurrency = &corevango.StrictConcurrency
StrictConcurrency forces session-loop-only write enforcement to panic even when DevMode is false. Useful for staging/canary environments.
var Timeout = corevango.Timeout
var Tx = corevango.Tx
Tx is an alias for Batch.
var TxNamed = corevango.TxNamed
TxNamed is a named transaction for observability.
var UnprocessableEntity = corevango.UnprocessableEntity
var Untracked = corevango.Untracked
Untracked reads signals without creating subscriptions.
WithNavigateParams adds query parameters to the navigation URL.
var WithReplace = server.WithReplace
WithReplace replaces the current history entry instead of pushing.
var WithoutScroll = server.WithoutScroll
WithoutScroll disables scrolling to top after navigation.
Functions ¶
func Async ¶
func Async(fn func(value any) (error, bool)) *form.AsyncValidator
Async creates an async validator for server-side checks.
func DecodeHookPayload ¶
DecodeHookPayload decodes hook payload data into a typed schema using strict JSON rules (unknown fields are rejected).
func DecodeIslandPayload ¶
func DecodeIslandPayload[T any](msg IslandMessage) (T, error)
DecodeIslandPayload decodes island payload data into a typed schema using strict JSON rules (unknown fields are rejected).
func DecodeWasmPayload ¶
func DecodeWasmPayload[T any](msg WasmMessage) (T, error)
DecodeWasmPayload decodes WASM payload data into a typed schema using strict JSON rules (unknown fields are rejected).
func DisableGlobalSignalRefresh ¶
DisableGlobalSignalRefresh disables periodic anti-entropy refresh for global signals.
func EqualTo ¶
func EqualTo(field string, msg string) *form.EqualToField
EqualTo returns a validator that checks if the value equals another field.
func Func ¶
Func wraps a render function as a Component. Deprecated: Use vango.Setup for all stateful components.
Example:
func Counter(initial int) vango.Component {
return vango.Setup(vango.NoProps{}, func(s vango.SetupCtx[vango.NoProps]) vango.RenderFn {
count := setup.Signal(&s, initial)
return func() *vango.VNode {
return Div(
H1(Textf("Count: %d", count.Get())),
Button(OnClick(count.Inc), Text("+")),
)
}
})
}
func GlobalSignalRefreshInterval ¶
GlobalSignalRefreshInterval configures the periodic anti-entropy refresh cadence for global signals from persistence.
func InSessionLoop ¶ added in v0.2.0
func InSessionLoop() bool
InSessionLoop reports whether the current goroutine is executing on the single-writer session loop.
func NotEqualTo ¶
func NotEqualTo(field string, msg string) *form.NotEqualToField
NotEqualTo returns a validator that ensures the value differs from another field.
func OnEvent ¶
OnEvent attaches a hook event handler to an element. This is spec-aligned: the handler receives `vango.HookEvent`.
func OnEventValidated ¶ added in v0.2.0
func OnEventValidated(name string, validate HookEventValidator, handler func(HookEvent)) vdom.Attr
OnEventValidated attaches a hook event handler plus exact-sink validation metadata for the named hook event.
func ParseForm ¶
ParseForm parses an HTTP form submission into the provided struct pointer. It returns form.ParseErrors when any fields fail to parse. ParseForm enforces DefaultFormMaxBytes to prevent memory DoS from large bodies.
func ParseFormData ¶
ParseFormData parses a Vango FormData submission into the provided struct pointer. It returns form.ParseErrors when any fields fail to parse.
func ParseFormWithLimit ¶
ParseFormWithLimit parses an HTTP form submission into the provided struct pointer, enforcing a maximum body size. It returns form.ParseErrors when fields fail to parse and *http.MaxBytesError when the size limit is exceeded.
func ResumeWindow ¶
ResumeWindow returns a pointer for configuring session resumption duration. Use NoResume() to disable resumption explicitly.
func UntrackedGet ¶
UntrackedGet reads a signal's value without subscribing.
func UserFromContext ¶
UserFromContext retrieves an authenticated user stored by WithUser. Returns nil when no user is present.
func UserFromContextAs ¶ added in v0.1.0
UserFromContextAs retrieves and type-asserts an authenticated user stored by WithUser. It returns the zero value of T and false when no user is present or the value has a different type.
Types ¶
type APIConfig ¶
type APIConfig struct {
// MaxBodyBytes is the maximum number of bytes read from the HTTP request body
// when an API handler declares a typed body parameter.
//
// Default: 1 MiB.
MaxBodyBytes int64
// RequireJSONContentType enforces that requests with a non-empty body specify a
// JSON Content-Type (application/json or application/*+json) when an API handler
// declares a structured (non-[]byte, non-string) body parameter.
//
// When false (default), missing Content-Type is accepted, but explicit non-JSON
// Content-Type is rejected.
RequireJSONContentType bool
}
APIConfig configures JSON API routes registered via app.API.
func DefaultAPIConfig ¶
func DefaultAPIConfig() APIConfig
DefaultAPIConfig returns an APIConfig with sensible defaults.
type APIHandler ¶
type APIHandler = any
APIHandler handles API requests and returns JSON responses. Multiple signatures are supported:
- func(ctx Ctx) (R, error) - no params or body
- func(ctx Ctx, params P) (R, error) - with route params
- func(ctx Ctx, body B) (R, error) - with request body
- func(ctx Ctx, params P, body B) (R, error) - with both
The framework inspects the handler signature to determine how to decode.
type ActionHandler ¶
type ActionHandler = corevango.ActionHandler
func OnActionError ¶
func OnActionError(fn func(error) *vdom.VNode) ActionHandler
func OnActionRunning ¶
func OnActionRunning(fn func() *vdom.VNode) ActionHandler
func OnActionSuccess ¶
func OnActionSuccess[R any](fn func(R) *vdom.VNode) ActionHandler
type ActionOption ¶
type ActionOption = corevango.ActionOption
type ActionRejection ¶
type ActionRejection = corevango.ActionRejection
type ActionRejectionReason ¶
type ActionRejectionReason = corevango.ActionRejectionReason
type ActionState ¶
type ActionState = corevango.ActionState
ActionState represents the current state of an action.
type AnimationEvent ¶
type AnimationEvent = corevango.AnimationEvent
type App ¶
type App struct {
// contains filtered or unexported fields
}
App is the main Vango application entry point. It wraps the server, router, and static file serving into a single http.Handler.
func New ¶
New creates a new Vango application with the given configuration. Returns an error when the configuration is invalid for non-DevMode environments.
func (*App) API ¶
func (a *App) API(method, path string, handler APIHandler)
API registers an API handler for the given HTTP method and path. API handlers return JSON responses.
Multiple handler signatures are supported:
// Simple handler (no params or body) func HealthGET(ctx vango.Ctx) (*HealthResponse, error) // With route parameters func UserGET(ctx vango.Ctx, p UserParams) (*User, error) // With request body func UserPOST(ctx vango.Ctx, body CreateUserRequest) (*User, error) // With both parameters and body func UserPUT(ctx vango.Ctx, p UserParams, body UpdateRequest) (*User, error)
func (*App) HandleUpload ¶
HandleUpload registers a CSRF-protected upload handler at the given path. This is the recommended way to mount upload handlers in Vango applications.
The handler is automatically wrapped with CSRF middleware when CSRF is enabled. Clients must include the CSRF token in the X-CSRF-Token header. Route middleware from app.Use/app.Middleware also applies to uploads.
Example:
store, _ := upload.NewDiskStore("/tmp/uploads", 10*1024*1024)
app.HandleUpload("/api/upload", store)
For custom configuration (max file size, allowed types, etc.), use HandleUploadWithConfig.
func (*App) HandleUploadWithConfig ¶
HandleUploadWithConfig registers a CSRF-protected upload handler with custom configuration.
The handler is automatically wrapped with CSRF middleware when CSRF is enabled. Clients must include the CSRF token in the X-CSRF-Token header. Route middleware from app.Use/app.Middleware also applies to uploads.
Example:
store, _ := upload.NewDiskStore("/tmp/uploads", 50*1024*1024)
app.HandleUploadWithConfig("/api/upload", store, &upload.Config{
MaxFileSize: 5 * 1024 * 1024, // 5MB
AllowedTypes: []string{"image/png", "image/jpeg"},
})
func (*App) Handler ¶
Handler returns the App as an http.Handler. This is useful for explicit type conversion or middleware wrapping.
func (*App) Layout ¶
func (a *App) Layout(path string, handler LayoutHandler)
Layout registers a layout handler for a path. Layouts registered separately apply to all pages under that path.
app.Layout("/admin", AdminLayout)
app.Page("/admin/dashboard", DashboardPage) // Uses AdminLayout
app.Page("/admin/users", UsersPage) // Uses AdminLayout
func (*App) Middleware ¶
func (a *App) Middleware(path string, mw ...RouteMiddleware)
Middleware registers route middleware for a path. Middleware runs before page/API/upload handlers and can:
Redirect (e.g., authentication checks)
Add data to context
Short-circuit the request
app.Middleware("/admin", authMiddleware)
func (*App) Page ¶
func (a *App) Page(path string, handler PageHandler, layouts ...LayoutHandler)
Page registers a page handler with optional layouts. The handler is called when a user navigates to the path.
Two handler signatures are supported:
// Static page (no route parameters)
func IndexPage(ctx vango.Ctx) *vango.VNode
// Dynamic page (with typed parameters)
type ShowParams struct {
ID int `param:"id"`
}
func ShowPage(ctx vango.Ctx, p ShowParams) *vango.VNode
Layouts wrap the page content. They are applied in order (root to leaf):
app.Page("/projects/:id", projects.ShowPage, RootLayout, ProjectsLayout)
func (*App) PageAction ¶ added in v0.1.0
PageAction registers a progressive page action for the given page route.
func (*App) Router ¶
Router returns the underlying router for advanced configuration. Most apps won't need this.
func (*App) Run ¶
Run starts the server and blocks until shutdown. This is a convenience method equivalent to http.ListenAndServe with graceful shutdown.
app, err := vango.New(cfg)
if err != nil {
log.Fatal(err)
}
routes.Register(app)
app.Run(":8080")
func (*App) RunAddr ¶
RunAddr starts the server and blocks until shutdown. This uses OS signals (SIGINT/SIGTERM) for graceful shutdown.
func (*App) ServeHTTP ¶
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements http.Handler. It routes requests to static files, the WebSocket endpoint, or page routes.
func (*App) Server ¶
Server returns the underlying server for advanced configuration. Most apps won't need this.
func (*App) SetErrorPage ¶
SetErrorPage sets the handler for error pages.
app.SetErrorPage(func(ctx vango.Ctx, err error) *vango.VNode {
return Div(H1(Textf("Error: %v", err)))
})
func (*App) SetNotFound ¶
func (a *App) SetNotFound(handler PageHandler)
SetNotFound sets the handler for 404 pages.
app.SetNotFound(func(ctx vango.Ctx) *vango.VNode {
return Div(H1(Text("Page Not Found")))
})
func (*App) UnsafeConfigReport ¶ added in v0.2.0
func (a *App) UnsafeConfigReport() server.UnsafeConfigReport
func (*App) Use ¶
func (a *App) Use(mw ...RouteMiddleware)
Use adds global middleware that applies to all routes. This includes page, API, and upload routes.
app.Use(loggingMiddleware, rateLimitMiddleware)
type AssetManifest ¶
AssetManifest holds the mapping from source asset paths to fingerprinted paths. Use LoadAssetManifest to load from a manifest.json file.
func LoadAssetManifest ¶
func LoadAssetManifest(path string) (*AssetManifest, error)
LoadAssetManifest loads a manifest.json file generated by the build process. The manifest maps source paths to fingerprinted paths:
{"vango.js": "vango.a1b2c3d4.min.js", "styles.css": "styles.e5f6g7h8.css"}
Example:
manifest, err := vango.LoadAssetManifest("dist/manifest.json")
if err != nil {
// In dev mode, this is expected - use passthrough resolver
log.Println("No manifest found, using passthrough resolver")
}
type AssetResolver ¶
AssetResolver provides asset path resolution with prefix support.
func NewAssetResolver ¶
func NewAssetResolver(m *AssetManifest, prefix string) AssetResolver
NewAssetResolver creates a resolver from a manifest with a path prefix. The prefix is prepended to all resolved paths.
Example:
manifest, _ := vango.LoadAssetManifest("dist/manifest.json")
resolver := vango.NewAssetResolver(manifest, "/public/")
// Configure server
config := server.DefaultServerConfig()
config.AssetResolver = resolver
func NewPassthroughResolver ¶
func NewPassthroughResolver(prefix string) AssetResolver
NewPassthroughResolver creates a resolver that returns paths unchanged. Use this in development mode where fingerprinting is disabled.
Example:
resolver := vango.NewPassthroughResolver("/public/")
resolver.Asset("vango.js") // "/public/vango.js"
type Attr ¶
Attr represents a single attribute in the VDOM. It is returned by the el DSL helpers (e.g. Class, ID, Attr) and can be used as a concrete type in user code (e.g. func TestID(string) vango.Attr).
type AuthCheckConfig ¶
type AuthCheckConfig = server.AuthCheckConfig
AuthCheckConfig configures periodic active revalidation. Use vango.Principal in AuthCheckConfig.Check callback signatures.
type AuthExpiredAction ¶
type AuthExpiredAction = server.AuthExpiredAction
AuthExpiredAction defines the action type for auth expiry.
type AuthExpiredConfig ¶
type AuthExpiredConfig = server.AuthExpiredConfig
AuthExpiredConfig defines behavior when auth expires.
type AuthExpiredReason ¶
type AuthExpiredReason = server.AuthExpiredReason
AuthExpiredReason provides structured context for auth expiry.
type AuthFailureMode ¶
type AuthFailureMode = server.AuthFailureMode
AuthFailureMode controls what happens when active checks fail.
type AuthResumePolicy ¶
type AuthResumePolicy = server.AuthResumePolicy
AuthResumePolicy controls how authenticated session resumes are validated.
type CacheControlStrategy ¶
type CacheControlStrategy int
CacheControlStrategy determines caching behavior for static files.
const ( // CacheControlNone adds no caching headers. // Use in development for instant updates. CacheControlNone CacheControlStrategy = iota // CacheControlProduction uses appropriate caching: // - Fingerprinted files (*.abc123.css): immutable, 1 year max-age // - Other files: short cache with revalidation CacheControlProduction )
type Cleanup ¶
type Config ¶
type Config struct {
// Session configures session behavior including durability and limits.
Session SessionConfig
// Static configures static file serving.
Static StaticConfig
// API configures JSON API routes (app.API).
API APIConfig
// Security configures security features (CSRF, origin checking, cookies).
Security SecurityConfig
// GlobalSignalPubSub is the broadcast backend for global signals.
// When nil, global signals update via eventual consistency only.
GlobalSignalPubSub GlobalBroadcastBackend
// GlobalSignalRefreshInterval controls the periodic anti-entropy refresh
// cadence for global signals from persistence.
// When persistence is available, this still runs with pubsub enabled so
// instances converge after missed broadcasts.
// nil means use the default (30 seconds).
// 0 disables refresh entirely.
GlobalSignalRefreshInterval *time.Duration
// DevMode enables development mode which disables security checks.
// SECURITY: NEVER use in production - this disables:
// - Origin checking (allows all origins)
// - CSRF validation
// - Secure cookie requirements
DevMode bool
// Logger is the structured logger for the application.
// If nil, slog.Default() is used.
Logger *slog.Logger
// Observability configures optional logging for mutations.
// All fields are opt-in and default to false.
Observability ObservabilityConfig
// Metrics configures the runtime metrics sink.
// When nil, metrics emission defaults to the internal collector.
Metrics MetricsSink
// StrictConcurrency forces session-loop-only write enforcement (signals,
// session keys) to panic even when pkg/vango.DevMode is false.
//
// Default: false (production-safe: drop + warn + metric).
//
// Useful for staging/canary environments to catch concurrency violations
// before they reach production.
StrictConcurrency bool
// OnSessionStart is called when a new WebSocket session is established.
// Use this to transfer data from the HTTP context (e.g., authenticated user)
// to the Vango session before the handshake completes.
//
// Example:
// OnSessionStart: func(httpCtx context.Context, s *vango.Session) {
// if user := myauth.UserFromContext(httpCtx); user != nil {
// auth.Set(s, user) // Use auth.Set to set presence flag
// }
// }
OnSessionStart func(httpCtx context.Context, s *Session)
// OnSessionResume is called when resuming an existing WebSocket session.
// Use this to rehydrate session data from the HTTP context (e.g., re-validate auth).
//
// Unlike OnSessionStart, this is called when resuming after disconnect.
// Return nil to allow the resume, or an error to reject it.
//
// Example:
// OnSessionResume: func(httpCtx context.Context, s *vango.Session) error {
// user, err := myauth.ValidateFromContext(httpCtx)
// if err != nil {
// return err // Reject resume if previously authenticated
// }
// if user != nil {
// auth.Set(s, user)
// }
// return nil
// }
OnSessionResume func(httpCtx context.Context, s *Session) error
// SSR configures server-side rendering behavior.
SSR SSRConfig
}
Config is the main application configuration. This is the user-friendly entry point for configuring a Vango app.
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a Config with sensible defaults.
type CookieOption ¶
type CookieOption = server.CookieOption
CookieOption configures cookie policy application.
func WithCookieHTTPOnly ¶
func WithCookieHTTPOnly(enabled bool) CookieOption
WithCookieHTTPOnly overrides the default HttpOnly behavior for a cookie.
type Ctx ¶
Ctx is the runtime context with full HTTP/navigation/session access. This is server.Ctx - the rich context that includes Path(), Param(), Query(), QueryParam(), Navigate(), User(), Session(), etc.
func UseCtx ¶
func UseCtx() Ctx
UseCtx returns the current runtime context. Returns nil if called outside of a render/effect/handler context.
Example:
func MyComponent() vango.Component {
return vango.Setup(vango.NoProps{}, func(s vango.SetupCtx[vango.NoProps]) vango.RenderFn {
return func() *vango.VNode {
ctx := vango.UseCtx()
path := ctx.Path()
userId := ctx.Param("id")
search := ctx.QueryParam("q")
return Div(Text(path))
}
})
}
type EventRateLimitConfig ¶
type EventRateLimitConfig = corevango.EventRateLimitConfig
EventRateLimitConfig configures token bucket rate limiting for events.
func DefaultDOMEventRateLimitConfig ¶
func DefaultDOMEventRateLimitConfig() *EventRateLimitConfig
DefaultDOMEventRateLimitConfig returns a default rate limit for standard DOM events.
func DefaultEventRateLimitConfig ¶
func DefaultEventRateLimitConfig() *EventRateLimitConfig
DefaultEventRateLimitConfig returns a conservative default rate limit.
type FormErrors ¶ added in v0.1.0
type FormErrors = corevango.FormErrors
type FormResult ¶ added in v0.1.0
type FormResult = corevango.FormResult
type GlobalBroadcastBackend ¶
type GlobalBroadcastBackend = corevango.GlobalBroadcastBackend
GlobalBroadcastBackend broadcasts updates to other instances.
func NewMemoryPubSub ¶
func NewMemoryPubSub() GlobalBroadcastBackend
NewMemoryPubSub creates an in-memory broadcast backend.
func NewRedisPubSub ¶
func NewRedisPubSub(client *redis.Client) GlobalBroadcastBackend
NewRedisPubSub creates a Redis-backed broadcast backend.
func ParsePubSubURL ¶
func ParsePubSubURL(raw string) (GlobalBroadcastBackend, error)
ParsePubSubURL creates a GlobalBroadcastBackend from a URL.
type Handler ¶
Handler handles a specific resource state in Match().
func OnError ¶
OnError handles the Error state in Resource.Match(). Error is when the fetch failed.
Example:
users.Match(
vango.OnError(func(err error) *vango.VNode {
return Div(Class("error"), Textf("Failed: %v", err))
}),
// ...
)
func OnLoading ¶
OnLoading handles the Loading state in Resource.Match(). Loading is when a fetch is in progress.
Example:
users.Match(
vango.OnLoading(func() *vango.VNode {
return Div(Class("spinner"), Text("Loading..."))
}),
// ...
)
func OnLoadingOrPending ¶
OnLoadingOrPending handles both Loading and Pending states in Resource.Match(). This is a convenience handler for showing a spinner during any waiting state.
Example:
users.Match(
vango.OnLoadingOrPending(func() *vango.VNode {
return Spinner() // Show spinner for both pending and loading
}),
vango.OnError(handleError),
vango.OnReady(renderUsers),
)
type HookEventValidator ¶
type HookEventValidator = corevango.HookEventValidator
HookEventValidator validates a hook event payload.
func HookSchemaValidator ¶
func HookSchemaValidator[T any](validate func(HookEvent, T) error) HookEventValidator
HookSchemaValidator builds a HookEventValidator that decodes hook payload data into a typed schema using strict JSON rules.
func HookValidatorMap ¶ added in v0.2.0
func HookValidatorMap(validators map[string]HookEventValidator) HookEventValidator
HookValidatorMap dispatches hook validation by exact event name.
type HostedSurfaceSecurityConfig ¶ added in v0.2.0
type HostedSurfaceSecurityConfig struct {
Enabled bool
// ProofSecret verifies X-Vango-Surface-Proof-* headers sent by the native
// host. Use 32+ random bytes and keep it separate from TokenSecret.
ProofSecret []byte
// TokenSecret signs server-minted hosted auth bootstrap tokens. It must be
// stable and server-only in non-dev mode.
TokenSecret []byte
// AllowedOrigins lists the trusted hosted web origins that may receive
// native hosted surface bootstrap.
AllowedOrigins []string
}
HostedSurfaceSecurityConfig configures signed hosted/native surface verification for first-party hosted native targets.
func HostedSurfaceSecurityFromEnv ¶ added in v0.2.0
func HostedSurfaceSecurityFromEnv(allowedOrigins ...string) HostedSurfaceSecurityConfig
HostedSurfaceSecurityFromEnv returns declarative hosted surface security using Vango's standard hosted macOS environment variables.
type InputEvent ¶
type InputEvent = corevango.InputEvent
type IslandMessage ¶
type IslandMessage = corevango.IslandMessage
IslandMessage is a message sent between an island and the server.
type IslandMessageValidator ¶
type IslandMessageValidator = corevango.IslandMessageValidator
IslandMessageValidator validates an island message payload.
func IslandSchemaValidator ¶
func IslandSchemaValidator[T any](validate func(IslandMessage, T) error) IslandMessageValidator
IslandSchemaValidator builds an IslandMessageValidator that decodes island payloads into a typed schema using strict JSON rules.
func IslandValidatorMap ¶ added in v0.2.0
func IslandValidatorMap(validators map[string]IslandMessageValidator) IslandMessageValidator
IslandValidatorMap dispatches island validation by exact island ID.
type KeyboardEvent ¶
type KeyboardEvent = corevango.KeyboardEvent
type LayoutHandler ¶
LayoutHandler wraps child content in a layout. Receives the render context and the slot containing child content.
func Layout(ctx vango.Ctx, children vango.Slot) *vango.VNode {
return Html(
Head(...),
Body(children),
)
}
type MetricsSink ¶
type MetricsSink = corevango.MetricsSink
MetricsSink is the interface used for runtime metric emission.
type ModifiedHandler ¶
type ModifiedHandler = corevango.ModifiedHandler
func Capture ¶ added in v0.1.0
func Capture(handler any) ModifiedHandler
func Hotkey ¶ added in v0.1.0
func Hotkey(key string, handler any) ModifiedHandler
func KeyWithModifiers ¶ added in v0.1.0
func KeyWithModifiers(key string, mods KeyMod, handler any) ModifiedHandler
func Keys ¶ added in v0.1.0
func Keys(keys []string, handler any) ModifiedHandler
func Once ¶ added in v0.1.0
func Once(handler any) ModifiedHandler
func Passive ¶ added in v0.1.0
func Passive(handler any) ModifiedHandler
func PreventDefault ¶
func PreventDefault(handler any) ModifiedHandler
func Self ¶ added in v0.1.0
func Self(handler any) ModifiedHandler
func StopPropagation ¶ added in v0.1.0
func StopPropagation(handler any) ModifiedHandler
type MouseEvent ¶
type MouseEvent = corevango.MouseEvent
type NavigateEvent ¶
type NavigateEvent = corevango.NavigateEvent
type NavigateOption ¶
type NavigateOption = server.NavigateOption
NavigateOption configures programmatic navigation.
type ObservabilityConfig ¶
type ObservabilityConfig = corevango.ObservabilityConfig
ObservabilityConfig configures optional observability features.
type PageHandler ¶
type PageHandler = any
PageHandler is a function that renders a page. Two signatures are supported:
- func(ctx Ctx) *VNode - static page with no route params
- func(ctx Ctx, params P) *VNode - dynamic page with typed params struct
For dynamic pages, the params struct uses `param` tags to map route parameters:
type ShowParams struct {
ID int `param:"id"`
}
func ShowPage(ctx vango.Ctx, p ShowParams) *vango.VNode { ... }
type PagedResponse ¶
type PagedResponse[T any] = corevango.PagedResponse[T]
PagedResponse is the standard paginated response payload wrapper.
type Principal ¶ added in v0.0.2
Principal is the authenticated principal type used by AuthCheck callbacks and Ctx principal accessors.
type ResizeEvent ¶
type ResizeEvent = corevango.ResizeEvent
type Resource ¶
Resource manages asynchronous data fetching and state. It provides reactive state tracking (Pending → Loading → Ready | Error) and methods for matching state in templates.
Allocate resources in Setup using setup.Resource or setup.ResourceKeyed.
Example:
return vango.Setup(vango.NoProps{}, func(s vango.SetupCtx[vango.NoProps]) vango.RenderFn {
users := setup.Resource(&s, func(ctx context.Context) ([]User, error) {
return api.FetchUsers(ctx)
})
return func() *vango.VNode {
return users.Match(
vango.OnLoading(func() *vango.VNode {
return Div(Text("Loading..."))
}),
vango.OnError(func(err error) *vango.VNode {
return Div(Textf("Error: %v", err))
}),
vango.OnReady(func(users []User) *vango.VNode {
return Ul(mapUsers(users)...)
}),
)
}
})
type ResourceOption ¶
type ResourceOption = corevango.ResourceOption
ResourceOption configures Resource behavior in Setup helpers.
func OnResourceError ¶
func OnResourceError(fn func(error)) ResourceOption
OnResourceError registers an error callback for resource loads.
func OnResourceSuccess ¶
func OnResourceSuccess(fn func(any)) ResourceOption
OnResourceSuccess registers a success callback for resource loads.
func RetryOnError ¶
func RetryOnError(count int, delay time.Duration) ResourceOption
RetryOnError configures retry count and delay.
func StaleTime ¶
func StaleTime(d time.Duration) ResourceOption
StaleTime sets the duration before data is considered stale.
type ResourceState ¶
ResourceState represents the current state of a resource.
const ( Pending ResourceState = corevango.Pending // Initial state, before first fetch Loading ResourceState = corevango.Loading // Fetch in progress Ready ResourceState = corevango.Ready // Data successfully loaded Error ResourceState = corevango.Error // Fetch failed (distinct from vango.Error) )
State constants for Resource. These are spec-aligned exports: use vango.Pending, vango.Loading, etc.
type Response ¶
Response wraps an API payload with optional metadata and HTTP status.
type RouteMiddleware ¶
type RouteMiddleware = router.Middleware
RouteMiddleware processes requests before they reach handlers.
type RouteMiddlewareFunc ¶
type RouteMiddlewareFunc = router.MiddlewareFunc
RouteMiddlewareFunc is a function adapter for RouteMiddleware.
Prefer this over importing github.com/vango-go/vango/pkg/router directly.
type RuntimeUnsafePermissions ¶ added in v0.2.0
type RuntimeUnsafePermissions = vdom.RuntimeUnsafePermissions
type SSRConfig ¶
type SSRConfig struct {
// EnableResourcePreload controls whether Resources are executed during SSR renders.
//
// When enabled, Setup component one-shot renders will:
// - run setup-registered pending effects (on an SSR single-writer loop)
// - wait for Resources to reach Ready/Error (bounded by ResourceTimeout)
//
// This improves progressive enhancement: SSR output can include loaded data
// even before a WebSocket session mounts.
//
// Default: true.
EnableResourcePreload *bool
// PageTimeout bounds the total SSR page render budget.
//
// This deadline flows through ctx.StdContext() during SSR and therefore caps:
// - route middleware
// - page handlers
// - layout assembly
// - HTML rendering
//
// 0 disables the framework-level SSR page deadline.
//
// Default: 5s.
PageTimeout *time.Duration
// ResourceTimeout bounds SSR resource preloading time only.
//
// When > 0, SSR-started resource fetches use a child context derived from
// the page context and capped by this timeout. SSR waits on that same
// preload budget.
//
// 0 disables waiting, but resources may still start opportunistically
// during SSR against the page context.
//
// Default: 300ms.
ResourceTimeout *time.Duration
}
SSRConfig configures server-side rendering behavior (HTTP GET renders).
type ScriptsOption ¶ added in v0.0.3
type ScriptsOption = vdom.ScriptsOption
ScriptsOption configures runtime script rendering helpers.
func WithAllowInsecureModuleOrigins ¶ added in v0.0.3
func WithAllowInsecureModuleOrigins() ScriptsOption
WithAllowInsecureModuleOrigins allows http: module imports on https: pages.
func WithAllowInsecureModuleOriginsAcknowledged ¶ added in v0.2.0
func WithAllowInsecureModuleOriginsAcknowledged(token string) ScriptsOption
WithAllowInsecureModuleOriginsAcknowledged allows insecure module origins with an explicit acknowledgement token.
func WithAllowSrcdoc ¶ added in v0.0.3
func WithAllowSrcdoc() ScriptsOption
WithAllowSrcdoc permits srcdoc updates on the thin client.
func WithAllowUnsafeRawHTML ¶ added in v0.0.3
func WithAllowUnsafeRawHTML() ScriptsOption
WithAllowUnsafeRawHTML disables raw HTML sanitization on the thin client.
func WithAllowUnsafeRawHTMLAcknowledged ¶ added in v0.2.0
func WithAllowUnsafeRawHTMLAcknowledged(token string) ScriptsOption
WithAllowUnsafeRawHTMLAcknowledged disables thin-client raw HTML sanitization with an explicit acknowledgement token.
func WithCSRFToken ¶ added in v0.0.3
func WithCSRFToken(token string) ScriptsOption
WithCSRFToken injects a CSRF token on the runtime script tag.
func WithDebug ¶ added in v0.0.3
func WithDebug() ScriptsOption
WithDebug enables client debug mode when rendering runtime scripts.
func WithModuleOrigins ¶ added in v0.0.3
func WithModuleOrigins(origins ...string) ScriptsOption
WithModuleOrigins sets allowed cross-origin module import origins.
func WithRuntimeUnsafePermissions ¶ added in v0.2.0
func WithRuntimeUnsafePermissions(perms RuntimeUnsafePermissions) ScriptsOption
WithRuntimeUnsafePermissions injects validated runtime unsafe permissions.
func WithScriptPath ¶ added in v0.0.3
func WithScriptPath(path string) ScriptsOption
WithScriptPath sets a custom thin-client script path.
func WithoutDefer ¶ added in v0.0.3
func WithoutDefer() ScriptsOption
WithoutDefer removes the defer attribute from the runtime script tag.
type ScrollEvent ¶
type ScrollEvent = corevango.ScrollEvent
type SecurityConfig ¶
type SecurityConfig struct {
// CSRFSecret is the secret key for CSRF token generation.
// If nil and CSRF is enabled in non-DevMode, a random secret is generated
// at startup (tokens won't survive server restarts).
// To disable CSRF protection entirely, set CSRFEnabled = false explicitly.
// For production, prefer a stable 32+ byte secret generated with crypto/rand and stored securely.
CSRFSecret []byte
// CSRFEnabled enables CSRF protection for state-changing HTTP endpoints.
// Default: true.
CSRFEnabled bool
// AllowedOrigins lists allowed WebSocket origins (scheme + host + optional port).
// Entries must not include path, query, or fragment.
// If empty and AllowSameOrigin is true, only same-origin requests are allowed.
// Example: []string{"https://myapp.com", "https://www.myapp.com"}
AllowedOrigins []string
// CustomOriginCheck allows a custom WebSocket origin validation function.
// Requires AllowCustomOriginPolicy to be true in production.
CustomOriginCheck func(r *http.Request) bool
// AllowedRedirectHosts lists hostnames (and optional ports) allowed for
// external redirects.
// Hostname-only entries authorize only the default ports (80 for http, 443
// for https). Use host:port for non-default ports.
// When empty, external redirects are rejected.
// Example: []string{"accounts.google.com", "auth.mycompany.com", "auth.mycompany.com:8443"}
AllowedRedirectHosts []string
// HostedSurfaceVerifier validates trusted hosted/native surface identity for
// page requests. When nil, raw hosted headers/query metadata are treated as
// untrusted hints only.
HostedSurfaceVerifier server.HostedSurfaceVerifyFunc
// HostedSurfaceTokenSecret signs short-lived hosted-auth bootstrap tokens for
// verified hosted surfaces. Use 32+ random bytes in non-dev mode.
HostedSurfaceTokenSecret []byte
// HostedSurface declaratively wires signed first-party hosted/native
// surface verification. This is the preferred setup for hosted native
// macOS and iOS targets; HostedSurfaceVerifier remains available for custom
// verification.
HostedSurface HostedSurfaceSecurityConfig
// AllowDevModeInNonLocalEnvironment acknowledges the security tradeoff of
// enabling DevMode alongside non-local / production-like server settings.
AllowDevModeInNonLocalEnvironment bool
// DevModeRiskAcceptance is a required explicit acknowledgement token for
// DevMode with non-local / production-like config.
DevModeRiskAcceptance string
// AllowedHosts lists hostnames (and optional ports) that are valid for this
// server.
// Hostname-only entries authorize only the request scheme's default port
// (80 for insecure requests, 443 for secure requests). Use host:port for
// non-default ports.
// When configured outside DevMode, App.ServeHTTP rejects requests with
// unapproved Host headers before routing to pages, APIs, uploads, static
// files, or runtime endpoints. Also used by WebSocketURL() and default CSP
// websocket-origin injection to prevent Host header poisoning attacks. If
// empty in production (non-DevMode), WebSocketURL() returns empty (fail
// secure), and app-level request routing remains compatible with deployments
// that enforce hosts at an external proxy.
// Example: []string{"myapp.com", "www.myapp.com", "myapp.com:8443"}
AllowedHosts []string
// CanonicalHost is the preferred hostname for URL generation.
// This must be host or host:port.
// When set, WebSocketURL() and default CSP websocket-origin injection use
// this host instead of the request host.
// Useful for normalizing "www" vs non-"www" variants.
CanonicalHost string
// PublicRuntimePrefix is the public mount prefix used when generating thin-client
// runtime endpoint URLs such as the live websocket path and client script URL.
//
// Examples:
// "" -> /_vango/live and /_vango/client.js
// "/app" -> /app/_vango/live and /app/_vango/client.js
//
// This affects generated public URLs only. If you mount Vango under a subpath,
// your external router or reverse proxy is still responsible for applying or
// stripping that prefix before requests reach the app.
PublicRuntimePrefix string
// AllowSameOrigin enables automatic same-origin validation.
// When true and AllowedOrigins is empty, validates that Origin header
// matches the request Host header.
// Default: true.
AllowSameOrigin bool
// AllowCustomOriginPolicy permits CustomOriginCheck without AllowedOrigins or AllowSameOrigin.
// SECURITY: avoid this in production unless you fully understand your policy.
AllowCustomOriginPolicy bool
// TrustedProxies lists reverse proxy IPs trusted for X-Forwarded-* headers.
// When set, forwarded proto headers are honored for secure cookie decisions.
// Default: nil (do not trust forwarded headers).
TrustedProxies []string
// CookieSecure sets the Secure flag on cookies set by the server.
// Should be true when using HTTPS.
// Default: true.
CookieSecure bool
// CookieHttpOnly sets the HttpOnly flag on cookies set by the server.
// Prevents JavaScript access to cookies that should not be read by JS.
// Default: true (except for CSRF cookies which need JS access).
CookieHttpOnly bool
// CookieSameSite sets the SameSite attribute for cookies set by the server.
// Lax is safe for most use cases and allows OAuth redirect flows.
// Default: http.SameSiteLaxMode.
CookieSameSite http.SameSite
// CookieDomain sets the Domain attribute for cookies.
// Empty string uses the current domain (most secure).
// Default: "".
CookieDomain string
// SecurityHeaders configures default HTTP security headers.
SecurityHeaders SecurityHeadersConfig
// URLPolicy controls scheme allowlists for URL-bearing attributes rendered by the server.
// If nil, defaults are used (href: http/https/mailto/tel/sms; resource/action: http/https).
// AllowSrcdoc and AllowUnsafeRawHTML are false by default and must be explicitly enabled.
URLPolicy *URLPolicyConfig
// AllowUnsafeRawHTMLInProduction acknowledges the security tradeoff of disabling
// framework raw-HTML sink sanitization in non-DevMode.
//
// When false (default), non-Dev configs that set URLPolicy.AllowUnsafeRawHTML are rejected.
//
// SECURITY: AllowUnsafeRawHTML can enable "gadget injection" of Vango runtime attributes
// (hooks/islands/WASM) when attacker-controlled HTML reaches a raw sink. Use only for
// fully trusted HTML with a strong CSP.
AllowUnsafeRawHTMLInProduction bool
// UnsafeRawHTMLRiskAcceptance is a required explicit acknowledgement token for
// non-dev raw HTML sink sanitization bypass.
UnsafeRawHTMLRiskAcceptance string
// AllowInsecureModuleOriginsInProduction acknowledges the security tradeoff of
// allowing insecure http: cross-origin island/WASM module imports on https:
// pages in non-dev mode.
AllowInsecureModuleOriginsInProduction bool
// InsecureModuleOriginsRiskAcceptance is a required explicit acknowledgement
// token for non-dev insecure cross-origin module origin allowance.
InsecureModuleOriginsRiskAcceptance string
}
SecurityConfig configures security features.
type SecurityHeadersConfig ¶
type SecurityHeadersConfig struct {
Enabled bool
// CSP controls Content-Security-Policy headers.
CSPEnabled bool
CSPReportOnly bool
CSP string
CSPOptions *server.CSPOptions
// HSTS controls Strict-Transport-Security headers.
HSTSMaxAge time.Duration
HSTSIncludeSubdomains bool
HSTSPreload bool
// FrameOptions controls the X-Frame-Options header ("DENY" or "SAMEORIGIN").
FrameOptions string
// ContentTypeNosniff controls the X-Content-Type-Options header.
ContentTypeNosniff bool
// ReferrerPolicy controls the Referrer-Policy header.
ReferrerPolicy string
// PermissionsPolicy controls the Permissions-Policy header.
PermissionsPolicy string
}
SecurityHeadersConfig configures default HTTP security headers. When Enabled is true, headers are applied unless explicitly set elsewhere.
func DefaultSecurityHeadersConfig ¶
func DefaultSecurityHeadersConfig() SecurityHeadersConfig
DefaultSecurityHeadersConfig returns secure default HTTP header settings.
func HardenedSecurityHeadersConfig ¶
func HardenedSecurityHeadersConfig() SecurityHeadersConfig
HardenedSecurityHeadersConfig returns a stricter security header profile. Compared to DefaultSecurityHeadersConfig, it disables inline styles in CSP.
type SessionConfig ¶
type SessionConfig struct {
// ResumeWindow is how long a disconnected session remains resumable.
// Within this window, a reconnecting client restores full session state.
// After this window, the session is permanently expired.
// nil means use the default (5 minutes).
// 0 disables resumption entirely (None tier).
ResumeWindow *time.Duration
// Store is the persistence backend for sessions.
// If nil, sessions are only stored in memory (lost on server restart).
// Use vango.NewMemoryStore(), vango.NewRedisStore(), or vango.NewSQLStore().
Store SessionStore
// MaxDetachedSessions is the maximum number of disconnected sessions
// to keep in memory. When exceeded, least recently used sessions are evicted.
// Default: 10000.
MaxDetachedSessions int
// MaxMemoryPerSessionBytes is the approximate in-memory cap per session.
// Sessions exceeding this may be evicted under memory pressure.
// 0 uses the server default.
MaxMemoryPerSessionBytes int64
// MaxSessionsPerIP is the maximum concurrent sessions from a single IP.
// Helps prevent DoS attacks. 0 means no limit.
// Default: 100.
MaxSessionsPerIP int
// MaxHandshakePathBytes limits the size of the `?path=` query parameter
// used during WebSocket handshake (decoded bytes, includes query string).
// 0 means no limit (not recommended).
// Default: 8KB.
MaxHandshakePathBytes int
// EvictionPolicy determines how detached sessions are evicted when limits are exceeded.
// Default: EvictionLRU.
EvictionPolicy SessionEvictionPolicy
// EvictOnIPLimit controls whether hitting MaxSessionsPerIP evicts the oldest
// detached session for that IP instead of rejecting the new session.
// Default: true when MaxSessionsPerIP > 0.
EvictOnIPLimit bool
// StormBudget configures rate limits for async primitives to prevent
// amplification bugs (e.g., effect triggers resource refetch triggers effect).
StormBudget *StormBudgetConfig
// AuthCheck configures authentication freshness checks for the session.
// When nil, no passive or active auth checks are performed.
AuthCheck *AuthCheckConfig
// AuthResumePolicy controls how authenticated session resumes are validated.
//
// Default: AuthResumePolicyStrict (requires authFunc or OnSessionResume for
// authenticated sessions to resume).
//
// Set to AuthResumePolicyTrustSessionID only if you understand the security
// implications. See server.AuthResumePolicy documentation for details.
AuthResumePolicy AuthResumePolicy
// AllowTrustSessionIDInProduction acknowledges the security tradeoff of
// AuthResumePolicyTrustSessionID in non-DevMode.
//
// When false (default), non-Dev configs that set TrustSessionID are rejected.
// TrustSessionID also requires:
// - TrustSessionIDRiskAcceptance = TrustSessionIDRiskAcceptanceV1
// - ResumeWindow <= 10s
// - Session.AuthCheck hardening:
// * Check configured
// * Interval > 0 and <= ResumeWindow
// * FailureMode = FailClosed
// * MaxStale <= ResumeWindow
AllowTrustSessionIDInProduction bool
// TrustSessionIDRiskAcceptance is a required explicit acknowledgement token
// for non-Dev AuthResumePolicyTrustSessionID usage.
//
// Set to TrustSessionIDRiskAcceptanceV1 when you intentionally accept the
// weaker logout/revocation semantics of TrustSessionID.
// Default: "" (not acknowledged).
TrustSessionIDRiskAcceptance string
// StateBudget configures limits on persisted state size.
// If nil, default limits are used.
StateBudget *StateBudgetConfig
// PersistenceSecret signs persisted blobs.
// This includes session persistence and global-signal blobs when
// global persistence/pubsub paths are enabled.
// Must be 32+ bytes of cryptographically random data.
PersistenceSecret []byte
// PersistenceSecretPrevious allows secret rotation.
// If set, blobs signed with this secret are accepted on resume.
PersistenceSecretPrevious []byte
// MaxBlobAge sets the maximum age for persisted session resume blobs.
// Blobs older than this are rejected during resume, triggering a fresh session.
// This applies to session resume only (not global signals).
// It helps prevent replay attacks with stale session data.
// 0 means no limit (default).
MaxBlobAge time.Duration
// HookEventValidator validates client hook event payloads.
// Return an error to reject the event.
// In production, startup warnings are emitted when this is unset.
HookEventValidator HookEventValidator
// DOMEventRateLimit applies per-session rate limiting to standard DOM events
// (click/input/scroll/etc., including navigation).
// RatePerSecond <= 0 disables rate limiting.
DOMEventRateLimit *EventRateLimitConfig
// HookEventRateLimit applies per-session rate limiting to hook events.
// RatePerSecond <= 0 disables rate limiting.
HookEventRateLimit *EventRateLimitConfig
// HookEventMaxPayloadBytes limits JSON size of hook event payloads.
// 0 means no limit.
HookEventMaxPayloadBytes int
// IslandMessageValidator validates island message payloads.
// Return an error to reject the message.
// In production, startup warnings are emitted when this is unset.
IslandMessageValidator IslandMessageValidator
// IslandEventRateLimit applies per-session rate limiting to island messages.
// RatePerSecond <= 0 disables rate limiting.
IslandEventRateLimit *EventRateLimitConfig
// IslandEventMaxPayloadBytes limits JSON size of island message payloads.
// 0 means no limit.
IslandEventMaxPayloadBytes int
// WasmMessageValidator validates WASM message payloads.
// Return an error to reject the message.
// In production, startup warnings are emitted when this is unset.
WasmMessageValidator WasmMessageValidator
// WasmEventRateLimit applies per-session rate limiting to WASM messages.
// RatePerSecond <= 0 disables rate limiting.
WasmEventRateLimit *EventRateLimitConfig
// WasmEventMaxPayloadBytes limits JSON size of WASM message payloads.
// 0 means no limit.
WasmEventMaxPayloadBytes int
// AllowRawHTMLInEventPayloads permits raw HTML or executable strings in
// hook/island/WASM payloads. Default: false.
// NOTE: Vango's unsafe-payload check is a heuristic substring filter,
// not a sanitizer. Always validate and/or sanitize untrusted payloads.
AllowRawHTMLInEventPayloads bool
// AllowHeuristicEventPayloadsInProduction keeps hook/island/WASM payload
// handling in heuristic-only mode in non-dev environments.
//
// This is a break-glass escape hatch. When false (default), non-dev sessions
// reject reachable hook/island/WASM sinks unless they are covered by a
// session-level validator or an exact-sink validated helper.
AllowHeuristicEventPayloadsInProduction bool
// HeuristicEventPayloadRiskAcceptance is a required explicit acknowledgement
// token for non-dev heuristic-only hook/island/WASM payload handling.
//
// Set to HeuristicEventPayloadRiskAcceptanceV1 when you intentionally accept
// heuristic-only event payload screening for reachable sinks in non-dev mode.
HeuristicEventPayloadRiskAcceptance string
}
SessionConfig configures session behavior.
func DefaultSessionConfig ¶
func DefaultSessionConfig() SessionConfig
DefaultSessionConfig returns a SessionConfig with sensible defaults.
type SessionEvictionPolicy ¶
type SessionEvictionPolicy = server.SessionEvictionPolicy
SessionEvictionPolicy determines which detached sessions are evicted first.
type SessionKey ¶
type SessionKey[T any] = corevango.SessionKey[T]
SessionKey is a typed, schema-safe session key.
func NewSessionKey ¶
func NewSessionKey[T any](name string, opts ...SessionKeyOption[T]) *SessionKey[T]
NewSessionKey creates a typed session key with a literal name.
type SessionKeyOption ¶
type SessionKeyOption[T any] = corevango.SessionKeyOption[T]
SessionKeyOption configures a SessionKey.
func Default ¶
func Default[T any](v T) SessionKeyOption[T]
Default sets the default value for a SessionKey.
type SessionStore ¶
type SessionStore = session.SessionStore
SessionStore is the interface for session persistence backends.
type StateBudgetConfig ¶
type StateBudgetConfig = corevango.StateBudgetConfig
StateBudgetConfig configures limits on persisted state size.
type StaticConfig ¶
type StaticConfig struct {
// Dir is the directory containing static files (e.g., "public").
// Files in this directory are served at the URL prefix.
//
// Vango serves static files through rooted access confined to this directory.
// Symlinks may be followed only when they resolve within Dir. Escaping and
// absolute-target symlinks are rejected.
Dir string
// Prefix is the URL path prefix for static files (e.g., "/").
// A file at public/styles.css with Prefix="/" is served at /styles.css.
// Default: "/".
Prefix string
// CacheControl determines caching behavior for static files.
// Default: CacheControlNone (no caching headers).
CacheControl CacheControlStrategy
// Compression enables gzip/brotli compression for static files.
// Default: false.
Compression bool
// Headers are custom headers to add to all static file responses.
Headers map[string]string
}
StaticConfig configures static file serving.
func DefaultStaticConfig ¶
func DefaultStaticConfig() StaticConfig
DefaultStaticConfig returns a StaticConfig with sensible defaults.
type StormBudgetConfig ¶
type StormBudgetConfig = server.StormBudgetConfig
StormBudgetConfig configures rate limits for async primitives. These limits help prevent amplification bugs where effects cascade into more effects, potentially causing performance issues.
type TouchEvent ¶
type TouchEvent = corevango.TouchEvent
type TransitionEvent ¶
type TransitionEvent = corevango.TransitionEvent
type URLEncoding ¶
URLEncoding specifies how complex types are serialized to URLs.
const ( // URLEncodingFlat serializes structs as flat params: ?cat=tech&sort=asc URLEncodingFlat URLEncoding = urlparam.EncodingFlat // URLEncodingJSON serializes as base64-encoded JSON: ?filter=eyJjYXQiOiJ0ZWNoIn0 URLEncodingJSON URLEncoding = urlparam.EncodingJSON // URLEncodingComma serializes arrays as comma-separated: ?tags=go,web,api URLEncodingComma URLEncoding = urlparam.EncodingComma )
type URLParamOption ¶
type URLParamOption = urlparam.URLParamOption
URLParamOption configures URL parameter behavior.
var ( // Push creates a new history entry (default behavior). Push URLParamOption = urlparam.Push // Replace updates URL without creating history entry (use for filters, search). Replace URLParamOption = urlparam.Replace )
URL parameter mode options
func Encoding ¶
func Encoding(e URLEncoding) URLParamOption
Encoding sets the URL encoding mode for complex types.
Example:
filters := setup.URLParam(&s, "", Filters{}, vango.Encoding(vango.URLEncodingFlat))
func URLDebounce ¶
func URLDebounce(d time.Duration) URLParamOption
Debounce delays URL updates by the specified duration. Use this for search inputs to avoid spamming the history.
Example:
search := setup.URLParam(&s, "q", "", vango.Replace, vango.URLDebounce(300*time.Millisecond))
type URLPolicyConfig ¶
type URLPolicyConfig struct {
// AllowedHrefSchemes controls href/xlink:href schemes.
// Empty or nil uses the defaults.
AllowedHrefSchemes []string
// AllowedResourceSchemes controls src/poster/srcset schemes.
// Empty or nil uses the defaults.
AllowedResourceSchemes []string
// AllowedActionSchemes controls action/formaction schemes.
// Empty or nil uses the resource schemes.
AllowedActionSchemes []string
// AllowSrcdoc enables server-side rendering of srcdoc attributes.
// Client-side still requires allowSrcdoc to be enabled.
AllowSrcdoc bool
// AllowUnsafeRawHTML disables framework raw-HTML sanitization for
// DangerouslySetInnerHTML/Raw and ResyncFull application on the client.
// Default: false (sanitize raw HTML).
//
// SECURITY: Enabling this allows raw HTML to bypass framework sanitization.
// Use only for fully trusted internal HTML with a strong CSP.
AllowUnsafeRawHTML bool
}
URLPolicyConfig configures allowed schemes for URL-bearing attributes.
type UnsafeConfigCode ¶ added in v0.2.0
type UnsafeConfigCode = server.UnsafeConfigCode
type UnsafeConfigEntry ¶ added in v0.2.0
type UnsafeConfigEntry = server.UnsafeConfigEntry
type UnsafeConfigReport ¶ added in v0.2.0
type UnsafeConfigReport = server.UnsafeConfigReport
type UnsafeConfigSeverity ¶ added in v0.2.0
type UnsafeConfigSeverity = server.UnsafeConfigSeverity
type UnsafeConfigState ¶ added in v0.2.0
type UnsafeConfigState = server.UnsafeConfigState
type VNode ¶
VNode represents a virtual DOM node.
func RuntimeScripts ¶ added in v0.0.3
func RuntimeScripts(ctx Ctx, opts ...ScriptsOption) *VNode
RuntimeScripts renders the thin-client runtime script plus canonical bootstrap JSON.
For ordinary browser requests this emits a normalized browser/web bootstrap. Adapters such as the macOS desktop runtime can inject richer bootstrap state into the request context, and this helper will carry it through automatically. When the current request has a CSRF token, RuntimeScripts also carries it onto the runtime script tag so the thin client can complete its handshake without requiring inline scripts in CSP.
type ValidationError ¶
type ValidationError = form.ValidationError
ValidationError represents a validation failure.
type Validator ¶
Validator is an interface for form field validation.
func AlphaNumeric ¶
AlphaNumeric validates that the value contains only letters and digits.
func DateBefore ¶
DateBefore validates that a date/time is before the given time.
func NonNegative ¶
NonNegative validates that a numeric value is >= 0.
type ValidatorFunc ¶
type ValidatorFunc = form.ValidatorFunc
ValidatorFunc is a function that implements Validator.
type WasmMessage ¶
type WasmMessage = corevango.WasmMessage
WasmMessage is a message sent between a WASM component and the server.
type WasmMessageValidator ¶
type WasmMessageValidator = corevango.WasmMessageValidator
WasmMessageValidator validates a WASM message payload.
func WasmSchemaValidator ¶
func WasmSchemaValidator[T any](validate func(WasmMessage, T) error) WasmMessageValidator
WasmSchemaValidator builds a WasmMessageValidator that decodes WASM payloads into a typed schema using strict JSON rules.
func WasmValidatorMap ¶ added in v0.2.0
func WasmValidatorMap(validators map[string]WasmMessageValidator) WasmMessageValidator
WasmValidatorMap dispatches WASM validation by exact component ID.
type WheelEvent ¶
type WheelEvent = corevango.WheelEvent
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
client
|
|
|
cmd
|
|
|
vango
command
|
|
|
vango-bench
command
|
|
|
This file re-exports vdom attribute helpers for the el package.
|
This file re-exports vdom attribute helpers for the el package. |
|
examples
|
|
|
desktop-macos/bridge
command
|
|
|
Package icon provides structured SVG icon rendering for Vango apps.
|
Package icon provides structured SVG icon rendering for Vango apps. |
|
internal
|
|
|
build
Package build provides production build functionality for Vango applications.
|
Package build provides production build functionality for Vango applications. |
|
cmd/gen-urlattrs
command
|
|
|
config
Package config provides configuration parsing for Vango projects.
|
Package config provides configuration parsing for Vango projects. |
|
dev
Package dev provides the development server and hot reload functionality.
|
Package dev provides the development server and hot reload functionality. |
|
errors
Package errors provides structured, actionable error messages for Vango.
|
Package errors provides structured, actionable error messages for Vango. |
|
icon/genlucide
command
|
|
|
tailwind
Package tailwind manages the Tailwind CSS standalone binary.
|
Package tailwind manages the Tailwind CSS standalone binary. |
|
templates
Package templates provides project scaffolding templates for vango create.
|
Package templates provides project scaffolding templates for vango create. |
|
pkg
|
|
|
assets
Package assets provides runtime resolution of fingerprinted asset paths.
|
Package assets provides runtime resolution of fingerprinted asset paths. |
|
auth
Package auth provides type-safe authentication helpers for Vango.
|
Package auth provides type-safe authentication helpers for Vango. |
|
auth/sessionauth
Package sessionauth provides a session-first auth adapter for Vango.
|
Package sessionauth provides a session-first auth adapter for Vango. |
|
authmw
Package authmw provides route-level authentication/authorization middleware.
|
Package authmw provides route-level authentication/authorization middleware. |
|
features
Package features provides higher-level abstractions for building Vango applications.
|
Package features provides higher-level abstractions for building Vango applications. |
|
features/context
Package context provides a type-safe dependency injection mechanism for Vango applications.
|
Package context provides a type-safe dependency injection mechanism for Vango applications. |
|
features/form
Package form provides type-safe form handling with validation for Vango applications.
|
Package form provides type-safe form handling with validation for Vango applications. |
|
features/hooks
Package hooks provides client-side interaction hooks for Vango components.
|
Package hooks provides client-side interaction hooks for Vango components. |
|
features/islands
Package islands provides JavaScript integration for Vango components.
|
Package islands provides JavaScript integration for Vango components. |
|
features/optimistic
Package optimistic provides instant visual feedback for user interactions.
|
Package optimistic provides instant visual feedback for user interactions. |
|
features/wasm
Package wasm provides WASM component helpers for Vango.
|
Package wasm provides WASM component helpers for Vango. |
|
middleware
Package middleware provides production-grade middleware for Vango applications.
|
Package middleware provides production-grade middleware for Vango applications. |
|
pref
Package pref provides user preference management with sync capabilities.
|
Package pref provides user preference management with sync capabilities. |
|
protocol
Package protocol implements the binary wire protocol for Vango V2.
|
Package protocol implements the binary wire protocol for Vango V2. |
|
render
Package render provides server-side rendering (SSR) for Vango components.
|
Package render provides server-side rendering (SSR) for Vango components. |
|
router
Package router implements file-based routing for Vango.
|
Package router implements file-based routing for Vango. |
|
server
Package server provides the server-side runtime for Vango's server-driven architecture.
|
Package server provides the server-side runtime for Vango's server-driven architecture. |
|
session
Package session provides session persistence and management for Vango.
|
Package session provides session persistence and management for Vango. |
|
toast
Package toast provides feedback notifications for Vango applications.
|
Package toast provides feedback notifications for Vango applications. |
|
upload
Package upload provides file upload handling for Vango.
|
Package upload provides file upload handling for Vango. |
|
urlparam
Package urlparam provides enhanced URL parameter synchronization for Vango.
|
Package urlparam provides enhanced URL parameter synchronization for Vango. |
|
vango
Package vango provides the reactive core for the Vango framework.
|
Package vango provides the reactive core for the Vango framework. |
|
vdom
Package vdom provides the Virtual DOM implementation for Vango.
|
Package vdom provides the Virtual DOM implementation for Vango. |
|
vtest
Package vtest provides a deterministic, server-side harness for testing Vango components without a browser.
|
Package vtest provides a deterministic, server-side harness for testing Vango components without a browser. |
|
tools
|
|
|
requirements_matrix/validate
command
|