API reference
Every exported name, generated from the source by go generate; a test fails when this page and the code disagree. Each name links to its pkg.go.dev entry, and each row has an anchor: /reference#via.WithSessionTTL. To install, see Getting started.
via 97 · h 170 · on 39 · expr 23 · topic 13 · vt 30 · vtbrowser 20
#via
The router, the pages mounted on it, the state handles a page renders, via.Ctx, sessions and the error surface. Router options are policy passed to via.NewRouter or via.Handler: a page cannot change them, which is why none of them is a method on a composition. Match a sentinel error with errors.Is and switch on PageError.Reason with a default: a status via does not emit today maps to ReasonInternal or ReasonBadRequest.
#Types
| Symbol | Does |
|---|---|
| Assets is the CSP-governed half of the document head: everything that loads or executes. | |
| The per-request binder, handed to every callback but View. It is not safe for concurrent use: call it only from the via callback it was given to. | |
| The context bounding this unit's work: the stream's on a live unit, the request's otherwise. Never nil. Watch it in a Tick or Listen handler to abandon a slow call against a dead socket. | |
| Subscribes the unit to a topic and runs the handler on the unit's own goroutine for every value, unsubscribing on disconnect. Makes the unit live. OnInit only. | |
| Runs once, when this unit's stream opens, after every Listen has subscribed. OnInit only; on a unit nothing made live it never runs. | |
| Runs when the unit's connection closes — stop subscriptions, release producers. OnInit only, and only meaningful on a unit something has made live. | |
| The mount pattern's named segment, decoded into T. A segment that will not decode answers 404 rather than a zero value, and naming a segment the pattern does not have panics. | |
| Navigates the browser after the current handler returns, from OnInit, OnReload, a PostForm submit or an action alike. The render that called it ships nothing. Only a relative path or a URL on this site's host or a trusted origin is followed; anything else is dropped and logged. | |
| Redirect to any http(s) URL, for a hand-off that leaves the site (OAuth, payment). Other schemes are still dropped. Build the target yourself; one taken from the request is an open redirect. | |
| The request behind this render. Its query string is populated on the GET and empty on every action, because an action's URL is the mount pattern and nothing else. | |
| The browser session — one value, Get/Put/Delete, ID and Rotate — resolved from the signed cookie and created lazily on the first write. | |
| Runs the handler every d for the life of the connection and re-renders the unit after each run; a d of 0 or less runs every second, with one warning. Makes the unit live. OnInit only. | |
| Head describes the router-wide document shell: the <html lang>, raw head markup, and the assets every page of the app carries. | |
| A State over a slice, with Append, Remove and Each. | |
| Append adds v to the end of this connection's list and schedules the push, like any Set. | |
| Each renders row(item) for every element, in order — sugar over via.Each(l.Get(), row), and like State.Display it marks the unit live. | |
| Remove deletes the element at i, shifting the rest left, and panics if i is out of range. | |
| MemorySessionStore is the process-local default store — a map guarded by a mutex, with CAS support (VersionedSessionStore). | |
| Delete implements SessionStore. | |
# MemorySessionStore.func (s *MemorySessionStore) Load(_ context.Context, id string) ([]byte, bool, error) | Load implements SessionStore. |
# MemorySessionStore.func (s *MemorySessionStore) LoadVersion(_ context.Context, id string) ([]byte, uint64, bool, error) | LoadVersion implements VersionedSessionStore. |
# MemorySessionStore.func (s *MemorySessionStore) Save(_ context.Context, id string, data []byte, ttl time.Duration) error | Save implements SessionStore. |
# MemorySessionStore.func (s *MemorySessionStore) SaveIf(_ context.Context, id string, data []byte, ttl time.Duration, version uint64) (bool, error) | SaveIf implements VersionedSessionStore. |
| Meta is what a mounted page declares about its own document, via the PageMeta() Meta hook on the mounted root. | |
| MountOption configures a single Mount call, as opposed to Option which configures the whole Router. | |
| Option configures a Handler or a NewRouter. | |
| Everything via knows about a failure it is about to answer, handed to the WithErrorPage handler. Status and Reason are the contract; Detail and Err are for logs and dev builds. | |
| Preload is one <link rel="preload">. | |
| The stable code an error page switches on: bad_request, forbidden, not_found, method_not_allowed, gone, too_large, internal, unavailable. One per status class, so a switch with a default is exhaustive. | |
| Router serves several via pages, each Mounted at its own path, behind one http.Handler. | |
| Shutdown with no deadline. | |
| ServeHTTP lazily runs r.init on first use, so a zero Router (var r via.Router) is ready to Mount and serve without an explicit constructor call. | |
| Drains the live half — stream goroutines, Tick timers, Listen subscriptions — and returns once it is quiet, or with ctx's error at its deadline, logging the tabs whose handler is still blocked. Call it before http.Server.Shutdown, which does not cancel the router's own context. | |
| Script is one <script>. | |
| Session is a browser session's value bag, resolved from the signed cookie, created lazily on the first write — an app that never stores anything stays cookieless. | |
| Delete clears the stored value; the session id and cookie survive, so a later Put on this same session starts from nothing rather than minting a new id. | |
| Ensure mints the session and issues its cookie if there is none yet, storing no value, and returns Session.ID. | |
| Get reads the session's value as T, returning the zero value and false when nothing is stored or the stored bytes no longer decode into T. | |
| ID is the session's stable identity: minted once, unchanged by Session.Rotate, "" when there is no session yet. | |
| Put stores v as the session's value. | |
| Rotate issues a fresh session id, carries the existing data to it, and re-sets the cookie — call it after every auth-state change (login, privilege elevation) so a fixed pre-auth id is invalidated. | |
| SessionStore is where session state lives between requests. | |
| Client-resident state that round-trips per request. | |
| Bind returns a two-way data-bind="<slot>" attribute for an input, sharing the signal's name with Display regardless of source order. | |
| Display renders the signal as a Datastar text-bound span. | |
| Get returns the server-side value: what the last Set wrote, or what the client posted back for a Bind()ed signal on this request. | |
| Ref returns the signal's Datastar expression — "$count" for a field Count, "$chat__draft" for a Draft inside an embedded Chat (the double underscore marks the child boundary; a plain nested struct joins with a single one) — for hand-written Datastar attributes the typed API does not cover: | |
| Set assigns the value and declares the slot, which is what carries the change to the client: a live action pushes a patch-signals frame, a plain action's element patch carries a data-signals restricted to the slots it wrote. | |
| Client-only state. Its name is _-prefixed, which Datastar's fetch filter drops, so the server never sees it. | |
| Bind returns a two-way data-bind="<slot>" attribute for an input. | |
| Display renders the signal as a Datastar text-bound span, showing the seed value until the client changes it. | |
| Ref returns the signal's Datastar expression — "$_open" for a field Open. | |
| Server-authoritative per-tab state, rendered as text and morphed when it changes. Rendering one makes its unit live. | |
| Display renders the current value as literal, escaped server text and marks its unit live, so server-held state alone earns a connection. | |
| Get returns this connection's value. | |
| Set assigns the value on this unit instance. | |
| Track keeps s equal to a store announced on t: it seeds s from load now, seeds it again once the stream has subscribed, and then applies every publish. | |
| Style is one stylesheet — Href for a <link rel="stylesheet">, Inline for a <style> admitted by the sha256 of its exact bytes. | |
| VersionedSessionStore is the optional half of SessionStore, for a backend that can make a write conditional on the revision it read. |
#Functions
| Symbol | Does |
|---|---|
| Renders a struct field as its own child, keyed by its position among the parent's Child calls. The argument must be a field selector: a composite literal would re-seed the child on every render. | |
| Renders row(item) for every item, in order, in place. Rows morph by position, so give a row a stable id when the order can change. | |
| A one-page app: a Router with root mounted at "/". It returns the Router rather than an http.Handler so the live half stays reachable. | |
| Seeds a List from a parent's composite literal, for a child that has no OnInit of its own to Set it in. | |
| Registers a page composition at an http.ServeMux pattern, serving that exact path and never a subtree: "/docs/" does not answer /docs/intro. root is taken by value, and the page's actions post to {path}/_via/a/{child}/{act}, so a {name...} or {$} wildcard, or one named child or act, panics. | |
| NewMemorySessionStore returns the default process-local store: a map that is lost on restart and invisible to every other pod. | |
| An empty router. Mount pages onto it, serve it, and Shutdown it when the server shuts down. | |
| A native multipart form whose submit is a real navigation, read back with ctx.Request().FormValue. | |
| Seeds a State from a parent's composite literal, for a child that has no OnInit of its own to Set it in. | |
| A State that seeds from load at every init of its unit, re-seeds once the stream has subscribed, then follows the topic. For a source fixed at mount; State.Track in OnInit is for one that depends on the request. | |
| Renders build() when cond holds and does not call it otherwise. cond decides what is dispatchable as well as what is drawn, so a handler inside a closed branch answers 410. |
#Options
| Symbol | Does |
|---|---|
| Renders via's failures as HTML documents instead of plain text. It applies to document responses only. | |
| The router-wide document shell: lang, raw head markup, and the assets every page carries. An invalid head panics at startup. | |
| Routes via's own diagnostics to l. Default is slog.Default(). | |
| Caps an action POST body, and how much of a form submit stays in RAM before spilling to a temp file (default 1 MiB). Over the cap answers 413. | |
| Caps how many live streams this router serves at once (default 10000; 0 or less panics); past the cap a connect is refused 503. The same number, up to 1024, caps actions parked waiting for their tab's stream; past it an action answers 503. | |
| Caps a native form submit's whole multipart body (default 8 MiB). Over the cap answers 413. | |
| How long an action POST waits for the tab's stream goroutine to pick it up before answering 503 and logging the tab as pinned (default 5s; 0 or less panics). An action that has started is waited for, since it writes the POST's own response. The same deadline covers the wait for a tab's stream that has not connected yet, capped at 2s: 410 if it has not come by then, and at once if via itself ended it. | |
| Forces Secure on the session cookie. Without it Secure follows TLS or the proxy's X-Forwarded-Proto / Forwarded header, so it is for a proxy that sends neither. | |
| Overrides the cookie name (default "via_session"). Set a distinct one per app when two via apps share a host. A name net/http would drop panics. | |
| The HMAC key signing the session cookie id; at least 16 bytes, or it panics, as an empty key or a second WithSessionKey does. Without the option, via falls back to the VIA_SESSION_KEY environment variable, and failing that mints a random per-process key, so those cookies survive neither a restart nor a second process. | |
| Points sessions at a shared, durable store instead of the default process-local map. Pair it with WithSessionKey; both are required past one pod, see Deploy. A second WithSessionStore panics. | |
| Caps one session store round-trip (default 5s); 0 or less panics. Without it a hung backend pins the request goroutine, since session calls survive client cancellation. | |
| How long a session may sit idle before it expires (default 24h); 0 or less panics. The window slides at one write per half-TTL, so a session can expire as little as half the TTL after its last request. | |
| Turns on origin enforcement for the action endpoint and the stream connect and allowlists one origin. Without any set, every action and the stream connect accept any origin and via logs a warning at startup — set this in production. Host case, a default port and a trailing "/" don't matter; a value with a path, query, fragment or userinfo panics. | |
| Adds 'unsafe-eval' to every page's script-src, for a library that compiles code from strings. The nonce and hashes stay. While set, via logs a warning at startup: a string that reaches eval, Function or setTimeout(string) runs as script. |
#Constants and variables
| Symbol | Does |
|---|---|
| Denies with a 403. For "you may not do this"; queue a ctx.Redirect instead for "please sign in". | |
| Return it from OnInit when the data the page needs no longer exists: the request was honest, so the answer is 404, not 500. Wrap it freely; errors.Is matches. | |
| The tab that would have bound this action is gone: its stream closed, or the id belongs to a render that no longer exists. The one failure a reload fixes. | |
| The session store could not be read for this request. The request was fine, a dependency is not; answer it like an outage. | |
| 400 — unusable action arg, malformed form or body | |
| 403 — untrusted origin, session mismatch, ErrForbidden | |
| 410 — the render that would bind this action is gone | |
| 500 — a hook or render failed | |
| 405 — the route exists, this method does not (a GET of an action URL) | |
| 404 — no such route, ErrNotFound, undecodable Param | |
| 413 — body over the cap | |
| 503 — the session store could not answer, or a live tab could not take the action |
#Lifecycle hooks
Four methods on your own type, duck-typed: a unit opts in by having one. A hook-named method with the wrong signature panics at Mount, and a near-miss name carrying a hook's exact signature is logged once.
| Method | Does |
|---|---|
View() h.H | The unit's markup, and the one required method. It takes no Ctx: whatever it draws was loaded into fields by OnInit. A missing or mistyped View on a mounted root is a compile error. |
OnInit(*via.Ctx) error | Loads request and session data, and registers the timers and subscriptions that make the unit live. It runs on every request that renders the unit — the GET, the stream connect, and each action on a page that is not streaming. |
OnReload(*via.Ctx) error | Runs after one of the unit's actions and before the render that answers it, so a handler that mutated a store re-reads here. Skipped behind a Redirect. |
PageMeta() via.Meta | The mounted root's own document: title, description, social cards, assets. Read after OnInit, on a render that writes a document, never on an SSE push. |
#h
Markup as Go calls: one function per HTML element and one per attribute, all returning h.H. Text and attribute values are escaped at render time, and URL attributes are scheme-checked.
#Types
| Symbol | Does |
|---|---|
| Attr is an H that renders inside the opening tag instead of the element body: h.Class, h.Href, h.Data, RawAttr, on.Click and Signal.Bind all return one. | |
| H is every node of a view: elements, text and attributes alike. | |
| Stringish is what Str accepts: ~string plus every built-in integer and float type, including named types whose underlying type is one of those. |
#Functions
| Symbol | Does |
|---|---|
| Accept is the accepted file types for a file input — ".png,image/jpeg". | |
| Action is the typed form-action attribute, gated like Src. | |
| Alt is the alternative text for an image or area. | |
| Aria builds an aria-<name> attribute — Aria("label", s) is aria-label. | |
| AutoComplete is the autocomplete hint — "off", "current-password". | |
| AutoFocus focuses the control on load when on. | |
| Class joins the given class names with spaces, skipping empty ones, and renders nothing at all when none survive — so Class(a, b) with both empty leaves no stray class="" behind, and a conditional class is just an empty string at the call site. | |
| Data builds a data-<name>="val" attribute; val is HTML-escaped at render. | |
| DataAttr sets the named attribute from the expression. | |
| DataClass toggles the named class while the expression is truthy. | |
| DataComputed declares a read-only signal derived from the expression. | |
| DataEffect runs the statements whenever a signal they read changes. | |
| DataIgnoreMorph renders a bare data-ignore-morph. | |
| DataIndicator names the signal Datastar holds true while a request from this element is in flight. | |
| DataOn runs the statements on the named DOM event. | |
| DataRef names the signal Datastar puts this element into. | |
| DataShow shows the element while the expression is truthy. | |
| DataStyle sets the named CSS property from the expression. | |
| DataText replaces the element's text with the expression's value. | |
| El builds an element with an arbitrary tag, for the handful of tags h has no named constructor for (a custom element, an SVG child). | |
| Enctype is the form encoding. | |
| For binds a label to the id of the control it labels. | |
| Href is the typed href attribute: http, https, mailto, tel and relative URLs pass through, any other scheme is neutralized to "#" and logged — a link must never become a script gadget. | |
| ID is the element id. | |
| Loop restarts media playback when on. | |
| Max is the maximum for a number, range or date input. | |
| MaxLength is the maximum accepted input length. | |
| Method is the form submission method — "get" or "post". | |
| Min is the minimum for a number, range or date input. | |
| MinLength is the minimum accepted input length, with the same caveat. | |
| Multiple allows multiple values on a select or file input when on. | |
| Name is the form field name, the key the value arrives under in a POST. | |
| NoValidate skips the browser's own form validation when on. | |
| PlaysInline plays video inline rather than fullscreen when on. | |
| RawAttr builds a name="val" attribute; val is HTML-escaped at render. | |
| ReadOnly makes a control read-only when on. | |
| Rel is the link relationship — "stylesheet", "noopener noreferrer". | |
| Required marks a control required when on. | |
| Reversed numbers an ordered list descending when on. | |
| Src is the typed src attribute, gated like Href but without mailto: and tel:. | |
| Step is the granularity for a number, range or date input. | |
| Str is the only way to put text in a view. | |
| Style is an inline style declaration. | |
| TabIndex is the tab order position. | |
| Target is the browsing context a link or form opens in. | |
| Title is the advisory title, shown as a tooltip. | |
| Value is the form field value, from any Stringish value. | |
#Datastar attributes
One typed helper per Datastar plugin, so the attribute key is spelled once. The helpers take an expr.Expr, and h.Data writes a plugin attribute h has no helper for.
| Helper | Attribute | Does |
|---|---|---|
h.DataShow(e) | data-show | Shows the element while the expression is truthy. |
h.DataText(e) | data-text | Replaces the element's text with the expression's value. |
h.DataClass(name, e) | data-class:<name> | Toggles the named class while the expression is truthy. |
h.DataAttr(name, e) | data-attr:<name> | Sets the named attribute from the expression. |
h.DataStyle(prop, e) | data-style:<prop> | Sets the named CSS property from the expression. |
h.DataOn(event, stmts…) | data-on:<event> | Runs the statements on that DOM event. Package on writes the same attribute. |
h.DataEffect(stmts…) | data-effect | Runs the statements whenever a signal they read changes. |
h.DataComputed(name, e) | data-computed:<name> | Declares a read-only signal derived from the expression. |
h.DataIndicator(sig) | data-indicator | Names the signal held true while a request from this element is in flight. |
h.DataRef(sig) | data-ref | Names the signal Datastar puts this element into. |
h.DataIgnoreMorph() | data-ignore-morph | Marks a subtree some JavaScript owns, so a live patch leaves it alone. |
#on
Each DOM event as a function, so a misspelled event or modifier does not compile. Each has a server form that posts a method and a CS twin that runs an expression in the browser.
#Types
| Symbol | Does |
|---|---|
| Bound is an action with its argument attached, made by Bind. | |
| Option is a Datastar event modifier. |
#Functions
| Symbol | Does |
|---|---|
| Attaches a typed value to the method, so the row's own datum rides with the event. Only an argument the render bound is dispatchable. | |
| Blur posts fn on blur. | |
| BlurCS runs e in the browser on blur. | |
| Change posts fn on change. | |
| ChangeCS runs e in the browser on change. | |
| Binds a DOM event to a method: the click posts to the method, not to a URL you invented. Takes a method value or an on.Bind, then options. | |
| The client-only twin of Click: runs the expression in the browser and posts nothing. | |
| DblClick posts fn on dblclick. | |
| DblClickCS runs e in the browser on dblclick. | |
| Posts a method on an event with no function of its own. The name must be lower-case, such as "pointerdown" or "via:patch"; anything else panics. | |
| The client-only twin of Event: runs the expression in the browser and posts nothing. | |
| Focus posts fn on focus. | |
| FocusCS runs e in the browser on focus. | |
| Input posts fn on input, which fires on every keystroke; pair it with WithDebounce. | |
| InputCS runs e in the browser on input. | |
| Keydown posts fn on keydown. | |
| KeydownCS runs e in the browser on keydown. | |
| Keyup posts fn on keyup. | |
| KeyupCS runs e in the browser on keyup. | |
| Load posts fn on load. | |
| LoadCS runs e in the browser on load. | |
| MouseEnter posts fn on mouseenter. | |
| MouseEnterCS runs e in the browser on mouseenter. | |
| MouseLeave posts fn on mouseleave. | |
| MouseLeaveCS runs e in the browser on mouseleave. | |
| Scroll posts fn on scroll; pair it with WithThrottle. | |
| ScrollCS runs e in the browser on scroll. | |
| Submit posts fn on submit. | |
| SubmitCS runs e in the browser on submit. |
#Options
| Symbol | Does |
|---|---|
| Runs the handler once the event stops firing for d. A non-positive d panics. | |
| Appends a Datastar modifier the typed options do not cover, such as "delay.300ms". A malformed or covered one panics. | |
| Runs the handler once. | |
| Fires only for targets outside the element. | |
| Calls preventDefault. | |
| Calls stopPropagation. | |
| Runs the handler at most once per d. A non-positive d panics. | |
| Listens on window. |
#expr
The small JavaScript expressions Datastar evaluates in the browser. Signal.Ref() is where one starts: it returns the signal's $name as an expr.Expr. Everything is checked except expr.Raw and the text of expr.Rawf.
#Types
| Symbol | Does |
|---|---|
| Expr is a Datastar client expression. | |
| Adds v to the signal in place. The receiver must be a bare $name. | |
| Writes v to the signal in place. The receiver must be a bare $name. | |
| Comparison with JavaScript's strict ===. | |
| Ge is >=. | |
| Gt is >. | |
| Le is <=. | |
| Lt is <. | |
| Comparison with JavaScript's strict !==. | |
| Negates the expression. | |
| The expression source. | |
| Negates the signal in place. The receiver must be a bare $name. |
#Functions
| Symbol | Does |
|---|---|
| Joins the expressions with &&. A single one is returned unchanged; none panics. | |
| Joins the expressions with ||. A single one is returned unchanged; none panics. | |
| Applies a function by name, which may be a dotted path ("console.log"). An invalid name panics. | |
| Adds or removes a class on the handler element, for feedback not worth a signal. A morph of the element resets it. | |
| Copies the text of the first element matching sel inside the handler element's parent, so a button copies the block beside it. | |
| Writes text to the clipboard. Browsers allow it only in a secure context and from a user gesture, so bind it to a click. | |
| Sequences statements, for an attribute that runs more than one. | |
| Emits js verbatim and unchecked. Never build one from user input. | |
| Splices checked expressions into unchecked text: each %s takes the next Expr verbatim. The text itself is emitted as written, like Raw. | |
| Encodes v as a JavaScript literal; an Expr passes through unchanged. An @ is escaped so Datastar does not read an @name( in it as an action call. |
#Constants and variables
| Symbol | Does |
|---|---|
| The element the attribute is written on. |
#topic
An in-process fan-out broker: one Publish reaches every subscriber. It is one process's memory, with no durability, replay or cross-pod delivery; put a real bus behind a Topic for those.
#Types
| Symbol | Does |
|---|---|
| Sub is a subscription. | |
| Drain removes and returns every queued value in publish order. | |
| Dropped reports how many values this subscription lost to its queue limit. | |
| Ready fires whenever the queue goes from empty to non-empty, and is closed by Stop. | |
| Stop unsubscribes and closes Ready, ending the reader's loop. | |
| WakeOn routes this subscription's wake-ups to ch as well as to Ready, so one reader can multiplex many subscriptions on a single channel — a live connection drives every ctx.Listen from its own select loop instead of spending a goroutine per subscription. | |
| Topic is a typed fan-out broker. | |
| NumSubs returns the number of live subscriptions — the head-count an app publishes as presence, and the number that must fall back to zero once every tab has disconnected. | |
| Publish queues v for every current subscriber and returns without blocking: no subscriber can stall the publisher or starve the others, and a unit may safely Publish to a topic it also listens to. | |
| Subscribe registers a new subscriber with DefaultLimit queue capacity. | |
| SubscribeLimit registers a new subscriber holding at most limit undelivered values. |
#Functions
| Symbol | Does |
|---|---|
| New builds a Topic with no subscribers. |
#Constants and variables
| Symbol | Does |
|---|---|
| DefaultLimit bounds how many undelivered values one subscriber may hold. |
#vt
A black-box test harness: drives a handler over real HTTP through via's public surface, so a test can fire an action or read a live stream without request plumbing.
#Types
| Symbol | Does |
|---|---|
| Action is a builder for an action POST. | |
| Body sets the raw JSON signal body (defaults to "{}"). | |
| Fire issues the POST and returns the status code and the response body. | |
| Header sets any other request header, such as the X-Forwarded-Proto a TLS-terminating proxy adds. | |
| Host overrides the request Host header (the authority the origin floor compares an Origin against). | |
| NoOrigin sends no origin signal at all, as a non-browser client does: the origin check admits it by default and refuses it under WithTrustedOrigin. | |
| Origin sets the Origin header and suppresses the default Sec-Fetch-Site, so the floor falls through to its Origin-host comparison. | |
| Over routes this action over c's stream: its viatab signal is set to c's tab id, and — unless Raw overrides it — Fire reads the action's URL off c's own pushed markup (see Conn.ActionURL) instead of a separate plain GET's render. | |
| Raw overrides the URL Fire posts to, bypassing the page-read lookup — for a test that deliberately wants a hand-built or stale URL (e.g. | |
| SecFetch sets the Sec-Fetch-Site header explicitly. | |
| Tab sets the viatab signal in the POST body, routing a live action to a connection's child — the same channel the real client uses, since Datastar ships the whole (underscore-filtered) signal store with every @post. | |
| App wraps a via handler under an httptest server, registered for cleanup. | |
| Action builds a POST to the n-th action the root renders, in document order (the root is child "r"). | |
| ChildAction builds a POST to the n-th action a child renders, in document order. | |
| Client returns the server's http.Client, wired to reach it (over the in-memory network for Serve, or trusting the self-signed cert for ServeTLS). | |
| Connect opens the per-tab SSE stream and reads the connect-time signals frame that carries the tab id, so the returned Conn is ready to route actions. | |
| ConnectAt is ConnectWith on a mount other than the root, for a Router with several pages. | |
| ConnectWith is Connect with a hand-written connect body — the page signals a real client ships with its @post('/_via/sse'). | |
| Get fetches path and returns the status code and body. | |
| URL is the server's base URL — the origin a test hand-rolls a request against when the builder methods above don't fit. | |
| Conn is an open SSE stream to a live child, carrying its per-connection tab id. | |
| ActionURL returns the currently-rendered URL of child's n-th action, in document order — read off the latest datastar-patch-elements frame that carries one, the same markup a browser's DOM would hold at this point, not a separate plain GET's render. | |
| Await blocks until a frame line containing needle arrives and returns that line, failing the test after 2s otherwise. | |
| AwaitClose blocks until the server ends the stream and returns the error that ended it — nil when the response terminated cleanly, which is what a graceful shutdown owes the client; a non-nil error means the client saw a truncated stream. | |
| Close cancels the stream. | |
| Peek takes the next buffered frame without blocking. | |
| TabID is the credential a live action must carry to route to this connection; Action.Over splices it in for you. |
#Functions
| Symbol | Does |
|---|---|
| Logger returns a logger that writes each record to t.Log, so via's diagnostics land in the test's own output. | |
| Serve mounts handler on an in-memory httptest server (req.TLS is nil), so the live-runtime suite can run under testing/synctest without touching a real socket. | |
| ServeTLS mounts handler on a TLS httptest server, so the action endpoint sees req.TLS != nil and the origin floor enforces the https scheme. |
#vtbrowser
Drives a handler in a real headless Chromium, for the bugs httptest cannot see. A separate module, so chromedp stays out of via's dependency graph; a test skips when no browser is found.
#Types
| Symbol | Does |
|---|---|
| Session is a live headless-browser tab bound to an httptest server running the handler. | |
| Click dispatches a real mouse click on the first node matching the CSS selector, waiting for it to become visible first. | |
| ConsoleErrors returns every console.error and uncaught exception the tab has produced. | |
| Eval runs a JavaScript expression and unmarshals its result into out — the escape hatch for assertions the named helpers don't cover. | |
| NewTab opens a second tab in the same browser, pointed at the same server — the way to drive multi-user behavior (fan-out, presence) where two live connections must coexist. | |
| Reload re-navigates the tab to the app root — a fresh document load, so a cookie set on the prior load (e.g. | |
| RequireCleanConsole fails the test if the tab logged any console error or threw any uncaught exception. | |
| Restart is a deploy: it takes the app's server off the air, leaves it down for the given gap, then serves handler again on the same host:port the tab is still pointed at. | |
| Sleep settles for d. | |
| Text returns the trimmed textContent of the first node matching the selector (empty string if none). | |
| Type focuses the first node matching the selector and sends text as real key events, so input/keydown listeners (and Datastar binds) fire as for a human. | |
| Value returns the value of the first input matching the selector. | |
| WaitBoundSignal blocks until the Datastar signal bound to selector (the slot named by its data-bind attribute) holds want. | |
| WaitEvalTrue polls a JavaScript boolean expression until it evaluates true, failing after defaultTimeout. | |
| WaitFor polls the trimmed textContent of selector until ok reports true, failing after defaultTimeout with the last observed text. | |
| WaitLiveConnected blocks until this tab's SSE stream has delivered its first frame. | |
| WaitLoaded blocks until the document has fully loaded, i.e. | |
| WaitTextContains polls until the first node matching selector has textContent containing want, absorbing SSE patch latency without a fixed sleep. | |
| WaitValue polls until the first input matching selector has value want. |
#Functions
| Symbol | Does |
|---|---|
| Open starts an httptest server for handler, launches headless Chromium, navigates to the app root, and returns the bound Session. |