vango

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Feb 24, 2026 License: MIT Imports: 36 Imported by: 0

README

Vango

Full Stack Go.
Build modern web apps with a single language, a single binary, and no client/server state synchronization. Solid's reactivity meets LiveView's architecture—in Go.

Go Reference Go Report Card License Discord

DocumentationExamplesManaged HostingDiscord


WIP / NOT LAUNCHED

Vango

Server-driven UI for Go. One language. One binary. Full interactivity.

Go Version License Documentation

Vango is a web framework that keeps your state and rendering on the server while delivering SPA-like interactivity to the browser. Write Go. Ship a single binary. Get modern web UX without the JavaScript build complexity.

func Counter(p CounterProps) vango.Component {
    return vango.Setup(p, func(s vango.SetupCtx[CounterProps]) vango.RenderFn {
        count := setup.Signal(&s, 0)

        return func() *vango.VNode {
            return Div(
                Button(OnClick(count.Dec), Text("-")),
                Span(Textf("%d", count.Get())),
                Button(OnClick(count.Inc), Text("+")),
            )
        }
    })
}

Why Vango?

If you've ever shipped a React app where a refactor silently broke user sessions, spent days debugging hydration mismatches, or wished you could just write Go instead of maintaining two codebases—Vango is designed to make those problems disappear.

🎯 One Language, Full Stack — Write your entire web app in Go. No separate frontend codebase, no client/server state sync, no hydration bugs.

⚡ Server State, Client Feel — State lives on the server. The browser runs a thin client that captures events and applies binary patches. Sub-50ms interactions feel instant.

🔒 Deploy-Safe by Default — Refactor fearlessly. Tooling tracks state identity so sessions survive deploys. Warm vs cold deploy impact is computed and CI-enforced—no silent user state loss.

🎨 Client Capabilities When You Need Them — Hooks for drag-and-drop, islands for rich editors, WASM for offline. First-class, not escape hatches.

Quick Start

go install github.com/vango-go/vango/cmd/vango@latest
vango create myapp && cd myapp
vango dev

Open http://localhost:8080.

The Programming Model

Setup/Closure: One Way to Write Components

Every stateful component follows the same pattern: Setup allocates state once, Render computes UI purely.

func TodoList(p TodoListProps) vango.Component {
    return vango.Setup(p, func(s vango.SetupCtx[TodoListProps]) vango.RenderFn {
        // Setup: allocate state (runs once per mount)
        items := setup.Signal(&s, []Todo{})
        newText := setup.Signal(&s, "")

        addTodo := setup.Action(&s,
            func(ctx context.Context, text string) (Todo, error) {
                return db.CreateTodo(ctx, text)
            },
            vango.DropWhileRunning(),
        )

        return func() *vango.VNode {
            // Render: pure function of state (runs on every update)
            return Div(
                Input(Value(newText.Get()), OnInput(newText.Set)),
                Button(OnClick(func() { addTodo.Run(newText.Get()) }), Text("Add")),
                RangeKeyed(items.Get(),
                    func(t Todo) string { return t.ID },
                    func(t Todo) *vango.VNode { return Li(Text(t.Text)) },
                ),
            )
        }
    })
}

No hook order rules. No accidental re-renders. No "stale closure" bugs.

Resources & Actions

Resources load data. Actions mutate it. Both run off the session loop so renders stay fast.

user := setup.ResourceKeyed(&s,
    func() int { return props.Get().UserID },
    func(ctx context.Context, id int) (*User, error) {
        return db.GetUser(ctx, id)
    },
)

return user.Match(
    vango.OnLoading(func() *vango.VNode { return Div(Text("Loading...")) }),
    vango.OnError(func(err error) *vango.VNode { return Div(Text(err.Error())) }),
    vango.OnReady(func(u *User) *vango.VNode { return Div(Text(u.Name)) }),
)

Full guide: Resources & Actions →

Deploy-Safe Persistence

Session state survives refreshes and deploys. You don't manage keys—tooling assigns stable IDs and tracks schema compatibility.

cartItems := setup.SharedSignal(&s, []CartItem{})  // Persisted per session
announcement := setup.GlobalSignal(&s, "")         // Shared across all sessions

Before shipping, you know exactly what will happen:

$ vango state plan
Added persisted IDs: 1
Classification: ✅ WARM DEPLOY

Cold deploys require explicit CI acknowledgment. No silent user state loss.

Full guide: Deploy-Safe State →

Client Hooks (Optional)

When server-driven isn't enough—drag-and-drop, focus management, third-party widgets—attach client behavior while keeping the server authoritative.

Ul(
    Hook("Sortable", map[string]any{"handle": ".drag-handle"}),
    OnEvent("reorder", func(e vango.HookEvent) {
        from, to := e.Int("fromIndex"), e.Int("toIndex")
        items.Set(reorder(items.Get(), from, to))
    }),
    RangeKeyed(items.Get(), ...),
)

Full guide: Client Capabilities →

Project Structure

myapp/
├── cmd/server/main.go          # Entry point
├── app/
│   ├── routes/                 # File-based routing
│   ├── components/             # Shared UI components
│   └── stores/                 # SessionKeys and state roots
├── internal/                   # Business logic
├── public/                     # Static assets
├── vango_state_manifest.json   # Commit this
└── vango_state_schema.json     # Commit this

What Vango Is Not

  • Not a SPA framework that pushes state to the browser
  • Not a template engine with ad hoc JavaScript sprinkled in
  • Not best-effort — deploy impact is computed, not guessed

Who Is Vango For?

  • Go developers who want a single-language web stack
  • React/Next refugees who want the UX without the complexity
  • LiveView fans who want Go performance and ecosystem
  • Teams shipping fast who can't afford silent state bugs

Documentation

Requirements

  • Go 1.23+ (toolchain defaults to Go 1.24.11 via go.mod)
  • Modern browser (ES2020+)

Contributing

See CONTRIBUTING.md.

License

MIT. See LICENSE.


DocsDiscussionsDiscord

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

View Source
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
)
View Source
const (
	// Failure modes
	FailOpenWithGrace = server.FailOpenWithGrace
	FailClosed        = server.FailClosed

	// Expiry actions
	ForceReload = server.ForceReload
	NavigateTo  = server.NavigateTo
	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
)
View Source
const (
	ActionRejectQueueFull        = corevango.ActionRejectQueueFull
	ActionRejectDropWhileRunning = corevango.ActionRejectDropWhileRunning
)
View Source
const (
	ActionIdle    = corevango.ActionIdle
	ActionRunning = corevango.ActionRunning
	ActionSuccess = corevango.ActionSuccess
	ActionError   = corevango.ActionError
)

ActionState constants

View Source
const (
	KindElement   = vdom.KindElement
	KindText      = vdom.KindText
	KindFragment  = vdom.KindFragment
	KindComponent = vdom.KindComponent
	KindRaw       = vdom.KindRaw
)

VKind constants

View Source
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

View Source
var ActionOnError = corevango.ActionOnError
View Source
var ActionOnStart = corevango.OnActionStart
View Source
var ActionOnSuccess = corevango.ActionOnSuccess
View Source
var ActionTxName = corevango.ActionTxName
View Source
var BadRequest = corevango.BadRequest
View Source
var BadRequestf = corevango.BadRequestf

Batch groups multiple signal updates into a single notification.

View Source
var CancelLatest = corevango.CancelLatest
View Source
var Conflict = corevango.Conflict
View Source
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.

View Source
var DropWhileRunning = corevango.DropWhileRunning
View Source
var ErrActionRunning = corevango.ErrActionRunning
View Source
var ErrAuthCheckPanicked = server.ErrAuthCheckPanicked
View Source
var ErrBudgetExceeded = corevango.ErrBudgetExceeded
View Source
var ErrQueueFull = corevango.ErrQueueFull
View Source
var Forbidden = corevango.Forbidden
View Source
var InternalError = corevango.InternalError
View Source
var Interval = corevango.Interval
View Source
var NotFound = corevango.NotFound
View Source
var OnActionRejected = corevango.OnActionRejected
View Source
var ServiceUnavailable = corevango.ServiceUnavailable
View Source
var StrictConcurrency = &corevango.StrictConcurrency

StrictConcurrency forces session-loop-only write enforcement to panic even when DevMode is false. Useful for staging/canary environments.

View Source
var Timeout = corevango.Timeout

Tx is an alias for Batch.

View Source
var TxNamed = corevango.TxNamed

TxNamed is a named transaction for observability.

View Source
var Unauthorized = corevango.Unauthorized
View Source
var UnprocessableEntity = corevango.UnprocessableEntity
View Source
var Untracked = corevango.Untracked

Untracked reads signals without creating subscriptions.

View Source
var WithNavigateParams = server.WithNavigateParams

WithNavigateParams adds query parameters to the navigation URL.

View Source
var WithReplace = server.WithReplace

WithReplace replaces the current history entry instead of pushing.

View Source
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

func DecodeHookPayload[T any](event HookEvent) (T, error)

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

func DisableGlobalSignalRefresh() *time.Duration

DisableGlobalSignalRefresh disables periodic global signal refresh.

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 Func(render func() *vdom.VNode) vdom.Component

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

func GlobalSignalRefreshInterval(d time.Duration) *time.Duration

GlobalSignalRefreshInterval configures the refresh cadence for global signals when no broadcast backend is configured.

func Hook

func Hook(name string, config any) vdom.Attr

func NoResume

func NoResume() *time.Duration

NoResume disables session resumption (ResumeWindow=0).

func NotEqualTo

func NotEqualTo(field string, msg string) *form.NotEqualToField

NotEqualTo returns a validator that ensures the value differs from another field.

func OnEvent

func OnEvent(name string, handler func(HookEvent)) vdom.Attr

OnEvent attaches a hook event handler to an element. This is spec-aligned: the handler receives `vango.HookEvent`.

func ParseForm

func ParseForm(r *http.Request, dst any) error

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

func ParseFormData(fd FormData, dst any) error

ParseFormData parses a Vango FormData submission into the provided struct pointer. It returns form.ParseErrors when any fields fail to parse.

func ParseFormWithLimit

func ParseFormWithLimit(r *http.Request, dst any, maxBytes int64) error

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

func ResumeWindow(d time.Duration) *time.Duration

ResumeWindow returns a pointer for configuring session resumption duration. Use NoResume() to disable resumption explicitly.

func Setup

func Setup[P any](p P, fn func(corevango.SetupCtx[P]) corevango.RenderFn) corevango.Component

Setup creates a stateful component with explicit props binding.

func UntrackedGet

func UntrackedGet[T any](s *Signal[T]) T

UntrackedGet reads a signal's value without subscribing.

func UserFromContext

func UserFromContext(ctx context.Context) any

UserFromContext retrieves an authenticated user stored by WithUser.

func WithUser

func WithUser(ctx context.Context, user any) context.Context

WithUser stores an authenticated user in a stdlib context for SSR and session bridging. Pair with UserFromContext and Config.OnSessionStart.

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 Action

type Action[A any, R any] = corevango.Action[A, R]

type ActionHandler

type ActionHandler[A any, R any] = corevango.ActionHandler[A, R]

func OnActionError

func OnActionError[A any, R any](fn func(error) *vdom.VNode) ActionHandler[A, R]

func OnActionIdle

func OnActionIdle[A any, R any](fn func() *vdom.VNode) ActionHandler[A, R]

Action match helpers

func OnActionRunning

func OnActionRunning[A any, R any](fn func() *vdom.VNode) ActionHandler[A, R]

func OnActionSuccess

func OnActionSuccess[A any, R any](fn func(R) *vdom.VNode) ActionHandler[A, R]

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 MustNew

func MustNew(cfg Config) *App

MustNew creates a new Vango application and panics if the configuration is invalid.

func New

func New(cfg Config) (*App, error)

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) Config

func (a *App) Config() Config

Config returns the app configuration.

func (*App) HandleUpload

func (a *App) HandleUpload(path string, store upload.Store)

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

func (a *App) HandleUploadWithConfig(path string, store upload.Store, config *upload.Config)

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

func (a *App) Handler() http.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) Router

func (a *App) Router() *router.Router

Router returns the underlying router for advanced configuration. Most apps won't need this.

func (*App) Run

func (a *App) Run(ctx context.Context, addr string) error

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

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

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

func (a *App) Server() *server.Server

Server returns the underlying server for advanced configuration. Most apps won't need this.

func (*App) SetErrorPage

func (a *App) SetErrorPage(handler func(Ctx, error) *VNode)

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) 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

type AssetManifest = assets.Manifest

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

type AssetResolver = assets.Resolver

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

type Attr = vdom.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.

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 Cleanup = corevango.Cleanup

func GoLatest

func GoLatest[K comparable, R any](
	key K,
	work func(ctx context.Context, key K) (R, error),
	apply func(result R, err error),
	opts ...corevango.GoLatestOption,
) Cleanup

func Subscribe

func Subscribe[T any](stream corevango.Stream[T], fn func(T), opts ...corevango.SubscribeOption) Cleanup

type Component

type Component = vdom.Component

Component is anything that can render to a VNode.

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 how often global signals refresh
	// from persistence when no broadcast backend is configured.
	// 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

type Ctx = server.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 DragEvent

type DragEvent = corevango.DragEvent

type DropEvent

type DropEvent = corevango.DropEvent

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 Form

type Form[T any] = form.Form[T]

Form is a type-safe form handler with validation support.

type FormData

type FormData = corevango.FormData

func NewFormData

func NewFormData(values map[string][]string) FormData

func NewFormDataFromSingle

func NewFormDataFromSingle(values map[string]string) FormData

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 HTTPError

type HTTPError = corevango.HTTPError

type Handler

type Handler[T any] = corevango.Handler[T]

Handler handles a specific resource state in Match().

func OnError

func OnError[T any](fn func(error) *vdom.VNode) Handler[T]

OnError handles the Error state in Resource.Match(). Error is when the fetch failed.

Example:

users.Match(
    vango.OnError[[]User](func(err error) *vango.VNode {
        return Div(Class("error"), Textf("Failed: %v", err))
    }),
    // ...
)

func OnLoading

func OnLoading[T any](fn func() *vdom.VNode) Handler[T]

OnLoading handles the Loading state in Resource.Match(). Loading is when a fetch is in progress.

Example:

users.Match(
    vango.OnLoading[[]User](func() *vango.VNode {
        return Div(Class("spinner"), Text("Loading..."))
    }),
    // ...
)

func OnLoadingOrPending

func OnLoadingOrPending[T any](fn func() *vdom.VNode) Handler[T]

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[[]User](func() *vango.VNode {
        return Spinner() // Show spinner for both pending and loading
    }),
    vango.OnError[[]User](handleError),
    vango.OnReady(renderUsers),
)

func OnPending

func OnPending[T any](fn func() *vdom.VNode) Handler[T]

OnPending handles the Pending state in Resource.Match(). Pending is the initial state before the first fetch begins.

Example:

users.Match(
    vango.OnPending[[]User](func() *vango.VNode {
        return Div(Text("Initializing..."))
    }),
    // ...
)

func OnReady

func OnReady[T any](fn func(T) *vdom.VNode) Handler[T]

OnReady handles the Ready state in Resource.Match(). Ready is when data has been successfully loaded.

Example:

users.Match(
    vango.OnReady(func(users []User) *vango.VNode {
        return Ul(mapUsers(users)...)
    }),
)

type HookEvent

type HookEvent = corevango.HookEvent

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.

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.

type KeyboardEvent

type KeyboardEvent = corevango.KeyboardEvent

type LayoutHandler

type LayoutHandler = func(Ctx, Slot) *VNode

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 Memo

type Memo[T any] = corevango.Memo[T]

type MetricsSink

type MetricsSink = corevango.MetricsSink

MetricsSink is the interface used for runtime metric emission.

type ModifiedHandler

type ModifiedHandler = corevango.ModifiedHandler

func PreventDefault

func PreventDefault(handler any) ModifiedHandler

type MouseEvent

type MouseEvent = corevango.MouseEvent
type NavigateEvent = corevango.NavigateEvent
type NavigateOption = server.NavigateOption

NavigateOption configures programmatic navigation.

type NoProps

type NoProps = corevango.NoProps

NoProps is the canonical empty-props type.

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 Props

type Props = vdom.Props

Props holds attributes and event handlers.

type PropsCell

type PropsCell[P any] = corevango.PropsCell[P]

PropsCell provides access to props with tracked and untracked reads.

type RenderFn

type RenderFn = corevango.RenderFn

RenderFn is the render closure returned by Setup callbacks.

type ResizeEvent

type ResizeEvent = corevango.ResizeEvent

type Resource

type Resource[T any] = corevango.Resource[T]

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[[]User](func() *vango.VNode {
                return Div(Text("Loading..."))
            }),
            vango.OnError[[]User](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

type ResourceState = corevango.State

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

type Response[T any] = corevango.Response[T]

Response wraps an API payload with optional metadata and HTTP status.

func Accepted

func Accepted[T any](data T) *Response[T]

Accepted creates a 202 Accepted typed API response.

func Created

func Created[T any](data T) *Response[T]

Created creates a 201 Created typed API response.

func NoContent

func NoContent[T any]() *Response[T]

NoContent creates a 204 No Content typed API response.

func OK

func OK[T any](data T) *Response[T]

OK creates a 200 OK typed API response.

func Paginated

func Paginated[T any](items []T, page, perPage, total int) *Response[PagedResponse[T]]

Paginated creates a paginated 200 OK typed API response.

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 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

	// ResourceTimeout bounds SSR resource preloading time.
	// 0 disables waiting (resources may remain Pending/Loading in SSR output).
	//
	// Default: 300ms.
	ResourceTimeout *time.Duration
}

SSRConfig configures server-side rendering behavior (HTTP GET renders).

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.
	// When empty, external redirects are rejected.
	// Example: []string{"accounts.google.com", "auth.mycompany.com", "auth.mycompany.com:8443"}
	AllowedRedirectHosts []string

	// AllowedHosts lists hostnames (and optional ports) that are valid for this server.
	// Used by WebSocketURL() to prevent Host header poisoning attacks.
	// If empty in production (non-DevMode), WebSocketURL() returns empty (fail secure).
	// Example: []string{"myapp.com", "www.myapp.com"}
	AllowedHosts []string

	// CanonicalHost is the preferred hostname for URL generation.
	// When set, WebSocketURL() returns this host instead of the request host.
	// Useful for normalizing "www" vs non-"www" variants.
	CanonicalHost 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
}

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 Session

type Session = server.Session

Session represents a client session.

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

	// 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 ResumeWindow <= 30s in non-DevMode.
	AllowTrustSessionIDInProduction bool

	// 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
}

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 SetupCtx

type SetupCtx[P any] = corevango.SetupCtx[P]

SetupCtx provides setup-time access to props and request context.

type Signal

type Signal[T any] = corevango.Signal[T]

Signal type aliases

type Slot

type Slot = corevango.Slot

Slot is an opaque container for child content.

func Children

func Children(children ...any) Slot

Children constructs a Slot from heterogeneous child inputs.

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.
	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 Touch

type Touch = corevango.Touch

type TouchEvent

type TouchEvent = corevango.TouchEvent

type TransitionEvent

type TransitionEvent = corevango.TransitionEvent

type URLEncoding

type URLEncoding = urlparam.Encoding

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 VKind

type VKind = vdom.VKind

VKind is the node type discriminator.

type VNode

type VNode = vdom.VNode

VNode represents a virtual DOM node.

type ValidationError

type ValidationError = form.ValidationError

ValidationError represents a validation failure.

type Validator

type Validator = form.Validator

Validator is an interface for form field validation.

func Alpha

func Alpha(msg string) Validator

Alpha validates that the value contains only ASCII letters.

func AlphaNumeric

func AlphaNumeric(msg string) Validator

AlphaNumeric validates that the value contains only letters and digits.

func Between

func Between(min, max any, msg string) Validator

Between validates that a numeric value is between min and max (inclusive).

func Custom

func Custom(fn func(value any) error) Validator

Custom creates a validator from a custom function.

func DateAfter

func DateAfter(t time.Time, msg string) Validator

DateAfter validates that a date/time is after the given time.

func DateBefore

func DateBefore(t time.Time, msg string) Validator

DateBefore validates that a date/time is before the given time.

func Email

func Email(msg string) Validator

Email validates that the value is a valid email address.

func Future

func Future(msg string) Validator

Future validates that a date/time is in the future.

func Max

func Max(n any, msg string) Validator

Max validates that a numeric value is <= n.

func MaxLength

func MaxLength(n int, msg string) Validator

MaxLength validates that a string has at most n characters.

func Min

func Min(n any, msg string) Validator

Min validates that a numeric value is >= n.

func MinLength

func MinLength(n int, msg string) Validator

MinLength validates that a string has at least n characters.

func NonNegative

func NonNegative(msg string) Validator

NonNegative validates that a numeric value is >= 0.

func Numeric

func Numeric(msg string) Validator

Numeric validates that the value contains only digits.

func Past

func Past(msg string) Validator

Past validates that a date/time is in the past.

func Pattern

func Pattern(pattern, msg string) Validator

Pattern validates that a string matches the given regular expression.

func Phone

func Phone(msg string) Validator

Phone validates that the value looks like a phone number.

func Positive

func Positive(msg string) Validator

Positive validates that a numeric value is > 0.

func Required

func Required(msg string) Validator

Required validates that the value is non-empty.

func URL

func URL(msg string) Validator

URL validates that the value is a valid URL.

func UUID

func UUID(msg string) Validator

UUID validates that the value is a valid UUID.

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.

type WheelEvent

type WheelEvent = corevango.WheelEvent

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.
internal
build
Package build provides production build functionality for Vango applications.
Package build provides production build functionality for Vango applications.
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.
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

Jump to

Keyboard shortcuts

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