Documentation
¶
Overview ¶
Package jaws provides a mechanism to create dynamic webpages using JavaScript and WebSockets.
It integrates well with Go's html/template package, but can be used without it. It can be used with any router that supports the standard http.Handler interface.
This package holds the core engine and the UI interfaces. The standard widgets (Span, Button, Select, Text, and so on) and the RequestWriter helper methods live in github.com/linkdata/jaws/lib/ui, and value binding lives in github.com/linkdata/jaws/lib/bind.
Locking ¶
The package uses a single, acyclic lock hierarchy. When more than one of these locks is held at once they must be acquired in this order, outermost first:
Jaws.mu -> Request.mu -> Session.mu
Request.muQueue and per-Element state are leaf locks taken below all of the above. Blocking work (channel sends, user callbacks) is always performed after snapshotting the needed state and releasing the relevant lock; see Session.Broadcast and Session.Close for the canonical pattern. The Request.SetContext transform is the deliberate exception: it runs while holding Request.mu so the read-modify-write is atomic, and therefore must not call back into the same Request or block.
UI value and widget types in the subpackages carry their own leaf locks that guard the bound value: the binders in github.com/linkdata/jaws/lib/bind, the JsVar in github.com/linkdata/jaws/lib/ui and the named values in github.com/linkdata/jaws/lib/named. These are leaves with respect to each other, acquired containing-before-contained (for example a named BoolArray's mutex is taken before a member Bool's). They sit strictly below the three core locks: every value type mutates the bound value under its value lock, releases it, and only then marks the Element dirty or broadcasts the change (which ultimately takes the outermost Jaws.mu), so a value lock is never held while a core lock is acquired. lib/bind, lib/ui and lib/named all follow this mutate-release-then-dirty pattern, and new value types must too. The safety of this rests on an invariant the deadlock detector cannot enforce (value locks are leaves distinct from Jaws.mu): no code path holding Jaws.mu, Request.mu or Session.mu ever calls into a UI value's Get/Set/Dirty methods, which are the only callers that take a value lock — were it otherwise, the later dirty step's Jaws.mu acquisition would invert the core lock order. Code holding any of the three core locks must therefore never invoke a UI value method.
A deliberate reverse edge lives in github.com/linkdata/jaws/lib/ui: ContainerHelper.reconcile holds its own widget mutex while calling Request.NewElement, which takes Request.mu — again leaf-before-core. It is safe for the same reason: no code path holding any of the three core locks ever invokes a widget's render or update method (the Serve loop calls JawsRender and JawsUpdate only after releasing Request.mu). Code holding Jaws.mu, Request.mu or Session.mu must therefore never call a container's render/update entry points. Note the widget mutex is a plain sync.Mutex, so deadlock.Debug cannot observe this inversion; the invariant is maintained by convention.
Element handlers are an intentional exception to the locking rules: they are populated only while an Element is rendered and are then read without a lock on the event goroutine. Element.JawsRender and Element.Freeze publish the final handler slice through the Element's atomic frozen flag; request event dispatch reads handlers only after observing that flag. This also covers child Elements rendered after a WebSocket connects: a preemptive event for a still-rendering Element is ignored. Handlers must not be added after JawsRender returns or Freeze is called. All builds enforce this through an internal chokepoint that drops late additions; debug builds panic instead.
Testing ¶
Always run the tests with the -race flag. Race builds set deadlock.Debug and deadlock.Enabled, exercising the deadlock lock-order detector described above and JaWS debug-gated runtime checks such as the late-handler panic. If the race detector is unavailable, use -tags "debug deadlock" so both categories stay active: the debug tag sets deadlock.Debug, while the deadlock tag enables the detector. Those JaWS debug branches are compile-time dead in normal builds, so a plain "go test" neither exercises them nor reports their statement coverage. Runtime tag-comparability checks in github.com/linkdata/jaws/lib/tag run in every build. CI builds with -race.
Index ¶
- Constants
- Variables
- func CallEventHandlers(ui any, elem *Element, wht what.What, value string) (err error)
- func ParseParams(params []any) (tags []any, handlers []any, attrs []string)
- type Auth
- type Click
- type ClickHandler
- type ConnectFn
- type Container
- type ContextMenuHandler
- type DefaultAuth
- type Element
- func (elem *Element) AddHandlers(h ...any)
- func (elem *Element) Append(htmlCode template.HTML)
- func (elem *Element) ApplyGetter(getter any) (tagValue any, attrs []template.HTMLAttr, err error)
- func (elem *Element) ApplyParams(params []any) (attrs []template.HTMLAttr)
- func (elem *Element) Deleted() bool
- func (elem *Element) Freeze()
- func (elem *Element) HasTag(tagValue any) bool
- func (elem *Element) InsertBefore(child *Element, htmlCode template.HTML)
- func (elem *Element) JawsRender(w io.Writer, params []any) (err error)
- func (elem *Element) JawsUpdate()
- func (elem *Element) Jid() jid.Jid
- func (elem *Element) JsCall(jsfunc, jsonstr string)
- func (elem *Element) Order(jidList []jid.Jid)
- func (elem *Element) Remove(child *Element)
- func (elem *Element) RemoveAttr(attr string)
- func (elem *Element) RemoveClass(cls string)
- func (elem *Element) Replace(htmlCode template.HTML)
- func (elem *Element) SetAttr(attr, value string)
- func (elem *Element) SetClass(cls string)
- func (elem *Element) SetInner(innerHTML template.HTML)
- func (elem *Element) SetValue(value string)
- func (elem *Element) String() string
- func (elem *Element) Tag(tags ...any)
- func (elem *Element) UI() UI
- type HandleFunc
- type InitHandler
- type InitialHTMLAttrHandler
- type InputFn
- type InputHandler
- type Jaws
- func (jw *Jaws) AddTemplateLookuper(tl TemplateLookuper) (err error)
- func (jw *Jaws) Alert(level, msg string)
- func (jw *Jaws) Append(target any, html template.HTML)
- func (jw *Jaws) Broadcast(msg wire.Message)
- func (jw *Jaws) Close()
- func (jw *Jaws) ContentSecurityPolicy() (s string)
- func (jw *Jaws) DefaultAuth() *DefaultAuth
- func (jw *Jaws) Delete(target any)
- func (jw *Jaws) Dirty(dirtyTags ...any)
- func (jw *Jaws) Done() <-chan struct{}
- func (jw *Jaws) FaviconURL() (s string)
- func (jw *Jaws) GenerateHeadHTML(extra ...string) (err error)
- func (jw *Jaws) GetSession(r *http.Request) (sess *Session)
- func (jw *Jaws) Insert(target any, childIndex int, html template.HTML)
- func (jw *Jaws) JsCall(target any, jsfunc, jsonstr string)
- func (jw *Jaws) Log(err error) error
- func (jw *Jaws) LookupTemplate(name string) *template.Template
- func (jw *Jaws) MustLog(err error)
- func (jw *Jaws) NewRequest(r *http.Request) (rq *Request)
- func (jw *Jaws) NewSession(w http.ResponseWriter, r *http.Request) (sess *Session)
- func (jw *Jaws) Pending() (n int)
- func (jw *Jaws) Redirect(url string)
- func (jw *Jaws) Reload()
- func (jw *Jaws) RemoveAttr(target any, attr string)
- func (jw *Jaws) RemoveClass(target any, cls string)
- func (jw *Jaws) RemoveTemplateLookuper(tl TemplateLookuper) (err error)
- func (jw *Jaws) Replace(target any, html template.HTML)
- func (jw *Jaws) RequestCount() (n int)
- func (jw *Jaws) RequestCounts() (total, active int)
- func (jw *Jaws) SecureHeadersMiddleware(next http.Handler) http.Handler
- func (jw *Jaws) Serve()
- func (jw *Jaws) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (jw *Jaws) ServeWithTimeout(requestTimeout time.Duration)
- func (jw *Jaws) SessionCount() (n int)
- func (jw *Jaws) SessionMiddleware(h http.Handler) http.Handler
- func (jw *Jaws) Sessions() (sessions []*Session)
- func (jw *Jaws) SetAttr(target any, attr, value string)
- func (jw *Jaws) SetClass(target any, cls string)
- func (jw *Jaws) SetInner(target any, innerHTML template.HTML)
- func (jw *Jaws) SetValue(target any, value string)
- func (jw *Jaws) Setup(handleFn HandleFunc, prefix string, extras ...any) (err error)
- func (jw *Jaws) TestServe(rq *Request, onPanic func(recovered any)) (inCh chan wire.WsMsg, outCh chan wire.WsMsg, bcastCh chan wire.Message, ...)
- func (jw *Jaws) UseRequest(jawsKey key.Key, r *http.Request) (rq *Request)
- type Jid
- type Logger
- type MakeAuthFn
- type Renderer
- type Request
- func (rq *Request) Alert(level, msg string)
- func (rq *Request) AlertError(err error)
- func (rq *Request) Cancel(err error)
- func (rq *Request) Context() (ctx context.Context)
- func (rq *Request) DeleteElement(elem *Element)
- func (rq *Request) Dirty(dirtyTags ...any)
- func (rq *Request) Get(key string) any
- func (rq *Request) GetConnectFn() (fn ConnectFn)
- func (rq *Request) GetElementByJid(jid Jid) (elem *Element)
- func (rq *Request) GetElements(tagValue any) (elems []*Element)
- func (rq *Request) HasTag(elem *Element, tagValue any) (yes bool)
- func (rq *Request) HeadHTML(w io.Writer) (err error)
- func (rq *Request) Initial() (r *http.Request)
- func (rq *Request) JawsKeyString() string
- func (rq *Request) Log(err error) error
- func (rq *Request) MarkWritten()
- func (rq *Request) MustLog(err error)
- func (rq *Request) NewElement(ui UI) *Element
- func (rq *Request) Redirect(url string)
- func (rq *Request) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (rq *Request) Session() (sess *Session)
- func (rq *Request) Set(key string, value any)
- func (rq *Request) SetConnectFn(fn ConnectFn)
- func (rq *Request) SetContext(fn func(oldCtx context.Context) (newCtx context.Context))
- func (rq *Request) String() string
- func (rq *Request) Tag(elem *Element, tagItems ...any)
- func (rq *Request) TagExpanded(elem *Element, expandedTags []any)
- func (rq *Request) TagsOf(elem *Element) (tags []any)
- func (rq *Request) TailHTML(w io.Writer) (err error)
- type Session
- func (sess *Session) Broadcast(msg wire.Message)
- func (sess *Session) Clear()
- func (sess *Session) Close() (cookie *http.Cookie)
- func (sess *Session) Cookie() (cookie *http.Cookie)
- func (sess *Session) CookieValue() (s string)
- func (sess *Session) Get(key string) (value any)
- func (sess *Session) ID() (id uint64)
- func (sess *Session) IP() (ip netip.Addr)
- func (sess *Session) Jaws() (jw *Jaws)
- func (sess *Session) Reload()
- func (sess *Session) Requests() (requests []*Request)
- func (sess *Session) Set(key string, value any)
- type SetupFunc
- type TemplateLookuper
- type UI
- type Updater
Constants ¶
const ( // DefaultUpdateInterval is the default browser update interval. DefaultUpdateInterval = time.Millisecond * 100 // DefaultWebSocketPingInterval is the default WebSocket keepalive ping interval. DefaultWebSocketPingInterval = time.Minute // DefaultWebSocketTimeout is the default time allowed for WebSocket connect and ping responses. DefaultWebSocketTimeout = time.Second * 10 // DefaultMaxPendingRequestsPerIP is the default maximum number of unclaimed // Requests allowed for each client IP. DefaultMaxPendingRequestsPerIP = 100 )
Variables ¶
var ErrEventHandlerPanic errEventHandlerPanic
ErrEventHandlerPanic is returned by CallEventHandlers when a user event handler panics.
Match it with errors.Is. When the recovered panic value is itself an error it is available via Unwrap (and thus errors.As / errors.Is); a non-error panic value appears only in the formatted message.
var ErrEventUnhandled = errEventUnhandled{}
ErrEventUnhandled returned by InputHandler.JawsInput, ClickHandler.JawsClick or ContextMenuHandler.JawsContextMenu causes the next available handler to be invoked.
var ErrInvalidChildElement = errors.New("invalid child element")
ErrInvalidChildElement indicates an invalid child Element.
Child operations report this error when the child is nil, deleted, unregistered, the receiver itself, or belongs to another Request.
var ErrInvalidChildIndex = errors.New("invalid child index")
ErrInvalidChildIndex indicates an invalid child index.
Jaws.Insert reports this error for a negative index. Use Jaws.Append to insert at the end.
var ErrJavascriptDisabled = errors.New("javascript is disabled")
ErrJavascriptDisabled is returned when the noscript probe indicates JavaScript is disabled.
var ErrNoWebSocketRequest errNoWebSocketRequest
ErrNoWebSocketRequest is returned when the WebSocket callback was not received within the timeout period. The most common reason is that the client is not using JavaScript.
var ErrRequestAlreadyClaimed = errors.New("request already claimed")
ErrRequestAlreadyClaimed is returned when Jaws.UseRequest is called more than once for a Request.
var ErrRequestCancelled errRequestCancelled
ErrRequestCancelled indicates a Request was cancelled.
The concrete error reachable via context.Cause on Request.Context wraps the underlying cancellation cause, so it can be matched with errors.Is and its cause retrieved with Unwrap. The exported sentinel itself carries no cause.
var ErrRequestOverloaded = errors.New("request overloaded")
ErrRequestOverloaded indicates a Request was torn down because it could not keep up with the messages addressed to it.
A Request is overloaded when its buffered broadcast channel or its internal event-call channel fills before it can drain them. Rather than silently dropping messages, which could leave the browser and backend in inconsistent and nonreproducible states, the Request is cancelled. The cancellation cause reachable via context.Cause on Request.Context wraps this sentinel, so it can be matched with errors.Is; the wrapped text identifies which channel overflowed.
var ErrServeAlreadyRunning = errors.New("serve loop already running")
ErrServeAlreadyRunning indicates the JaWS processing loop is already running.
var ErrTooManyPendingRequests errTooManyPendingRequests
ErrTooManyPendingRequests indicates an older pending Request was evicted because its client IP had reached Jaws.MaxPendingRequestsPerIP.
var ErrValueUnchanged = errors.New("value unchanged")
ErrValueUnchanged reports a successful no-op set: there was no error, but the underlying value already equaled the desired value.
Setter-style implementations (the JawsSet / JawsSetPath methods in github.com/linkdata/jaws/lib/ui and github.com/linkdata/jawstree) return it, and callers test for it with errors.Is. It lives in this package so all implementations share one error identity.
var ErrWebSocketIPMismatch errWebSocketIPMismatch
ErrWebSocketIPMismatch is returned when the WebSocket callback for a Request arrives from a different client IP than the initial HTTP request.
var ErrWebsocketOriginMissing = errors.New("websocket request missing Origin header")
ErrWebsocketOriginMissing is returned when a WebSocket request has no Origin header.
var ErrWebsocketOriginNoInitial = errors.New("websocket Origin cannot be validated: no initial request")
ErrWebsocketOriginNoInitial is returned when origin validation cannot run because the Request has no initial HTTP request to compare against. The check fails closed rather than accepting an unverified Origin.
var ErrWebsocketOriginWrongHost = errors.New("websocket Origin host mismatch")
ErrWebsocketOriginWrongHost is returned when a WebSocket Origin host does not match the initial request host.
var ErrWebsocketOriginWrongScheme = errors.New("websocket Origin not http or https")
ErrWebsocketOriginWrongScheme is returned when a WebSocket Origin is not HTTP or HTTPS.
Functions ¶
func CallEventHandlers ¶ added in v0.300.0
CallEventHandlers calls the event handlers for the given Element.
Recovers from panics in user-provided handlers, returning them as errors.
Request event dispatch calls this only after the Element is frozen, publishing the completed handler slice before its lock-free read. A direct caller must not run it concurrently with rendering or handler registration.
func ParseParams ¶ added in v0.60.0
ParseParams parses the parameters passed to UI helpers when creating a new Element, returning UI tags, event handlers and HTML attributes.
Unlike Element.ApplyGetter, which is given the primary getter, ParseParams only recognizes InputFn, InputHandler, ClickHandler and ContextMenuHandler. A param implementing InitHandler or InitialHTMLAttrHandler is treated only as a tag here; its JawsInit / JawsInitialHTMLAttr are intentionally invoked only for the primary getter.
A param recognized as an event handler is appended to handlers, and if it is also usable as a tag (comparable, per usableAsTag) it is additionally appended to tags, so a comparable handler is returned in both slices.
Types ¶
type Auth ¶ added in v0.85.0
type Auth interface {
// Data returns authenticated user data, or nil.
Data() map[string]any
// Email returns the authenticated user email, or an empty string.
Email() string
// IsAdmin reports whether the authenticated user has administrator access.
IsAdmin() bool
}
Auth describes authentication data available to templates through ui.With.
type Click ¶ added in v0.400.0
type Click struct {
// Name is the event target name. Parsing off the wire normalizes it: leading
// and trailing whitespace is trimmed and internal whitespace runs collapse to a
// single space, so it does not round-trip losslessly through [Click.String].
Name string
X float64 // X is the browser clientX coordinate in CSS pixels.
Y float64 // Y is the browser clientY coordinate in CSS pixels.
Shift bool // Shift reports whether the Shift key was held during the event.
Control bool // Control reports whether the Control key was held during the event.
Alt bool // Alt reports whether the Alt key was held during the event.
}
Click identifies a browser click-like event, pointer location and modifier state.
func (Click) String ¶ added in v0.400.0
String formats clk for the JaWS wire protocol.
It is not a lossless inverse of parsing: a Click.Name with leading, trailing or repeated internal whitespace is normalized when parsed back (see the Name field). The production wire direction is browser-to-server (parse only).
type ClickHandler ¶ added in v0.31.0
type ClickHandler interface {
// JawsClick is called for non-input-origin browser clicks.
//
// The client sends clicks from an [Element]'s HTML element and from
// non-form-control descendants. Clicks whose event target is an input,
// select, textarea or option element, or inside one, are left to native
// input handling and do not invoke JawsClick on an ancestor.
//
// [Click.Name] is the first name HTML attribute or 'button' textContent
// found while walking from the event target up through its ancestors. If none
// is found it falls back to the event target's HTML id, so it is empty only
// when the target has no id either.
JawsClick(elem *Element, click Click) (err error)
}
ClickHandler handles click events sent from the browser.
type ConnectFn ¶
ConnectFn can be used to interact with a Request before message processing starts. Returning an error causes the Request to abort, and the WebSocket connection to close.
type Container ¶ added in v0.31.0
type Container interface {
// JawsContains returns the current child [UI] values contained by elem.
//
// The returned [UI] values must be comparable, since they are used as map keys
// (see [UI] for the comparability requirement), and the slice contents must not
// be modified after returning it. A child UI may be returned repeatedly for
// the same Request, but must not be shared with a different Request.
JawsContains(elem *Element) (contents []UI)
}
Container is implemented by UI values that render a dynamic list of child UI values.
type ContextMenuHandler ¶ added in v0.400.0
type ContextMenuHandler interface {
// JawsContextMenu is called for non-input-origin browser context menus.
//
// The client sends context-menu events from an [Element]'s HTML element and
// from non-form-control descendants. Events whose target is an input, select,
// textarea or option element, or inside one, are left to native browser
// handling and do not invoke JawsContextMenu on an ancestor.
JawsContextMenu(elem *Element, click Click) (err error)
}
ContextMenuHandler handles context-menu events sent from the browser.
type DefaultAuth ¶ added in v0.300.0
type DefaultAuth struct {
// contains filtered or unexported fields
}
DefaultAuth is the permissive default Auth implementation used for templates when Jaws.MakeAuth is nil.
SECURITY: DefaultAuth.IsAdmin always returns true. Because it is substituted whenever Jaws.MakeAuth is unset, a template that gates privileged UI on {{if .Auth.IsAdmin}} will render that UI to EVERY visitor on any instance that forgot to set Jaws.MakeAuth. Data and Email are fail-safe (nil / empty); only IsAdmin is fail-open. Always set Jaws.MakeAuth in production, and treat a nil MakeAuth as "no authorization configured", not "deny".
func (*DefaultAuth) Data ¶ added in v0.300.0
func (*DefaultAuth) Data() map[string]any
Data returns no authenticated user data.
func (*DefaultAuth) Email ¶ added in v0.300.0
func (*DefaultAuth) Email() string
Email returns an empty authenticated user email.
func (*DefaultAuth) IsAdmin ¶ added in v0.300.0
func (da *DefaultAuth) IsAdmin() bool
IsAdmin returns true for every caller.
If a logger was supplied at construction, it logs a one-time warning that Jaws.MakeAuth is unset and authorization is fail-open.
type Element ¶ added in v0.31.0
type Element struct {
*Request // (read-only) the Request the Element belongs to
// contains filtered or unexported fields
}
Element is an instance of a Request, a UI object and a Jid.
An Element pointer supplied to a render, update or event handler is borrowed for that call. A request-scoped widget may retain child Elements it creates between its render and update calls within the same Request lifecycle, but should access them only from those calls. Do not retain an Element in longer-lived application state or pass it to background work: the embedded Request may later be pooled and reused for another connection.
func (*Element) AddHandlers ¶ added in v0.300.0
AddHandlers adds the given handlers to the Element.
It must be called while the Element is being rendered, before any event can be processed for it; see the package "Locking" documentation. Handlers added after Element.JawsRender has returned (or Element.Freeze has been called) are dropped; debug builds panic.
func (*Element) Append ¶ added in v0.31.0
Append appends a new HTML element as a child to the current one.
Call this while the Element is rendering or updating, when a send pass is imminent. To change the Element in response to a browser event, mark it dirty with Request.Dirty instead: a change queued directly from an event handler is flushed only when the processing loop is next woken, which on an otherwise-idle request is not guaranteed to be prompt (see [Element.queue]).
func (*Element) ApplyGetter ¶ added in v0.75.0
ApplyGetter examines getter and resolves its tag candidate.
If getter implements tag.TagGetter, the candidate is its returned value; otherwise the candidate is getter itself. TagGetter values, supported tag slices and runtime-comparable candidates are passed to Element.Tag for normal validation. Other non-comparable candidates are not automatically tagged, matching ParseParams.
If getter is an InputHandler, ClickHandler, ContextMenuHandler or InitialHTMLAttrHandler, relevant values are added to the Element.
Finally, if getter is an InitHandler, its JawsInit function is called.
Returns the tag that was added (nil if none was added, whether because getter was nil or its candidate was not usable as a tag), any initial HTML attrs provided by InitialHTMLAttrHandler, and any error returned from JawsInit() if it was called.
If the Element is already frozen and getter is an event handler, the handler is not added: in production with a Jaws.Logger configured this is logged and tag and init processing still occur, while debug builds and servers without a Logger panic via reportMisuse, aborting before tag and init processing. A non-event-handler getter never calls reportMisuse, so its tag and init processing always occur.
func (*Element) ApplyParams ¶ added in v0.60.0
ApplyParams parses the parameters passed to UI() when creating a new Element, adding UI tags, adding any additional event handlers found.
Returns the list of HTML attributes found, if any.
Handlers found in params are added only while the Element is mutable; after it is frozen (Element.JawsRender returning or Element.Freeze) they are dropped (debug builds panic), though tags and HTML attributes are still processed.
func (*Element) Deleted ¶ added in v0.600.0
Deleted reports whether the Element has been removed from its Request.
Element.JawsRender, Element.JawsUpdate and the queue helpers are no-ops on a deleted Element. A request-scoped widget that retains child Elements it creates between render and update calls within one Request lifecycle can use Deleted to detect and discard children removed out-of-band before reuse. Deleted is not a lifetime check: it does not report whether the embedded Request still represents the owning connection or make that Request safe to use after its lifecycle.
func (*Element) Freeze ¶ added in v0.500.0
func (elem *Element) Freeze()
Freeze marks the Element's handlers as final, as Element.JawsRender does on return. After Freeze, the handler-mutating methods (AddHandlers, ApplyParams, ApplyGetter) drop handlers; debug builds panic. Use this for elements registered for updates without being rendered.
func (*Element) InsertBefore ¶ added in v0.601.0
InsertBefore inserts new HTML immediately before child.
child must be a live, distinct Element belonging to the same Request as elem. Violations are reported as ErrInvalidChildElement, and no browser command is queued. The browser also verifies that child is a direct DOM child of elem before applying the insertion.
Call this while elem is rendering or updating, when a send pass is imminent. To insert HTML at the same child index in every element matching a tag, use Jaws.Insert.
func (*Element) JawsRender ¶ added in v0.55.0
JawsRender calls Renderer.JawsRender for this Element.
Do not call this yourself unless it is from within another JawsRender implementation.
func (*Element) JawsUpdate ¶ added in v0.55.0
func (elem *Element) JawsUpdate()
JawsUpdate calls Updater.JawsUpdate for this Element.
Do not call this yourself unless it is from within another JawsUpdate implementation.
func (*Element) Jid ¶ added in v0.31.0
Jid returns the JaWS ID for this Element, unique within its Request.
func (*Element) JsCall ¶ added in v0.75.0
JsCall queues a browser JavaScript function path call for the Element.
In the receiving browser, jsfunc is resolved as a path from window and called with JSON.parse(jsonstr); the Element is not passed as this or as an argument.
Call this while the Element is rendering or updating, when a send pass is imminent; a call queued directly from an event handler is only flushed when the processing loop is next woken (see [Element.queue]). To call JavaScript for every element matching a tag, use Jaws.JsCall.
func (*Element) Order ¶ added in v0.31.0
Order reorders the HTML elements.
Call this while the Element is rendering or updating, when a send pass is imminent. To change the Element in response to a browser event, mark it dirty with Request.Dirty instead: a change queued directly from an event handler is flushed only when the processing loop is next woken, which on an otherwise-idle request is not guaranteed to be prompt (see [Element.queue]).
func (*Element) Remove ¶ added in v0.31.0
Remove removes child from the browser and its Request registry.
child must be a live, distinct Element belonging to the same Request as elem. Violations are reported as ErrInvalidChildElement, and neither the DOM nor the registry is changed. The caller is responsible for ensuring child is a direct DOM child of elem; the browser verifies that relationship before applying the removal.
Call this while the Element is rendering or updating, when a send pass is imminent. To change the Element in response to a browser event, mark it dirty with Request.Dirty instead: a change queued directly from an event handler is flushed only when the processing loop is next woken, which on an otherwise-idle request is not guaranteed to be prompt (see [Element.queue]).
func (*Element) RemoveAttr ¶ added in v0.31.0
RemoveAttr queues sending a request to remove an attribute to the browser for the Element.
Call this while the Element is rendering or updating, when a send pass is imminent. To change the Element in response to a browser event, mark it dirty with Request.Dirty instead: a change queued directly from an event handler is flushed only when the processing loop is next woken, which on an otherwise-idle request is not guaranteed to be prompt (see [Element.queue]).
func (*Element) RemoveClass ¶ added in v0.31.0
RemoveClass queues sending a request to remove a class to the browser for the Element.
Call this while the Element is rendering or updating, when a send pass is imminent. To change the Element in response to a browser event, mark it dirty with Request.Dirty instead: a change queued directly from an event handler is flushed only when the processing loop is next woken, which on an otherwise-idle request is not guaranteed to be prompt (see [Element.queue]).
func (*Element) Replace ¶ added in v0.31.0
Replace replaces the Element's entire HTML DOM node with new HTML code.
The trusted HTML should preserve the element identity by putting the element's own JaWS id on the replacement root element, normally as id="Jid.N". Replace is not an HTML validator: it performs only a lightweight textual guard for that expected id attribute. If the guard does not find it, the call is a programming error: debug builds panic and production builds report it via Jaws.MustLog and skip the replacement.
Call this while the Element is rendering or updating, when a send pass is imminent. To change the Element in response to a browser event, mark it dirty with Request.Dirty instead: a change queued directly from an event handler is flushed only when the processing loop is next woken, which on an otherwise-idle request is not guaranteed to be prompt (see [Element.queue]).
func (*Element) SetAttr ¶ added in v0.31.0
SetAttr queues sending a new attribute value to the browser for the Element.
The value parameter must be the unescaped logical attribute value. It is sent to the browser DOM and used as the value argument to setAttribute().
Call this while the Element is rendering or updating, when a send pass is imminent. To change the Element in response to a browser event, mark it dirty with Request.Dirty instead: a change queued directly from an event handler is flushed only when the processing loop is next woken, which on an otherwise-idle request is not guaranteed to be prompt (see [Element.queue]).
func (*Element) SetClass ¶ added in v0.31.0
SetClass queues sending a class to the browser for the Element.
Call this while the Element is rendering or updating, when a send pass is imminent. To change the Element in response to a browser event, mark it dirty with Request.Dirty instead: a change queued directly from an event handler is flushed only when the processing loop is next woken, which on an otherwise-idle request is not guaranteed to be prompt (see [Element.queue]).
func (*Element) SetInner ¶ added in v0.31.0
SetInner queues sending new inner HTML content to the browser for the Element.
Call this while the Element is rendering or updating, when a send pass is imminent. To change the Element in response to a browser event, mark it dirty with Request.Dirty instead: a change queued directly from an event handler is flushed only when the processing loop is next woken, which on an otherwise-idle request is not guaranteed to be prompt (see [Element.queue]).
func (*Element) SetValue ¶ added in v0.31.0
SetValue queues sending a new current input value in textual form to the browser for the Element.
Call this while the Element is rendering or updating, when a send pass is imminent. To change the Element in response to a browser event, mark it dirty with Request.Dirty instead: a change queued directly from an event handler is flushed only when the processing loop is next woken, which on an otherwise-idle request is not guaranteed to be prompt (see [Element.queue]).
type HandleFunc ¶ added in v0.111.6
HandleFunc matches the signature of http.ServeMux.Handle.
type InitHandler ¶ added in v0.110.0
InitHandler allows initializing UI getters and setters before their use.
You can of course initialize them in the call from the template engine, but at that point you don't have access to the Element, Request.Context or Request.Session.
type InitialHTMLAttrHandler ¶ added in v0.400.0
type InitialHTMLAttrHandler interface {
// JawsInitialHTMLAttr is called when an [Element] is initially rendered,
// and may return an initial HTML attribute string to write out.
JawsInitialHTMLAttr(elem *Element) (s template.HTMLAttr)
}
InitialHTMLAttrHandler can add attributes during initial Element rendering.
type InputFn ¶ added in v0.401.0
InputFn is the signature of an input handling function. JaWS calls it for an input or set message received from JavaScript over the WebSocket connection, and for a hook message, which tests use to invoke the handler synchronously (see what.Hook).
type InputHandler ¶ added in v0.401.0
type InputHandler interface {
// JawsInput is called when an [Element] receives a browser input event.
JawsInput(elem *Element, value string) (err error)
}
InputHandler handles input events sent from the browser.
type Jaws ¶
type Jaws struct {
CookieName string // Name for session cookies; defaults to a name derived from the executable ([assets.DefaultCookieName]), falling back to "jaws"
AutoSession bool // Create a session during a successful WebSocket upgrade when a Request has none. Defaults to false.
TrustForwardedHeaders bool // Trust X-Forwarded-* headers: governs the session cookie Secure flag (X-Forwarded-Proto) and the client IP used for session/request binding (X-Forwarded-For/X-Real-IP). Defaults to false; only enable behind a single reverse proxy you control that sets these headers.
Logger Logger // Optional logger to use
Debug bool // Set to true to enable debug info in generated HTML code. Call GenerateHeadHTML after changing it.
MakeAuth MakeAuthFn // Function to create ui.With.Auth for Templates. If nil, templates get the fail-open DefaultAuth (IsAdmin()==true for everyone); set it to enforce authorization. See DefaultAuth.
BaseContext context.Context // Non-nil base context for Requests, set to context.Background() in New()
WebSocketPingInterval time.Duration // Interval between keepalive pings on active WebSocket connections. Defaults to DefaultWebSocketPingInterval. Set <=0 to disable keepalive pings.
MaxPendingRequestsPerIP int // Maximum number of unclaimed Requests per client IP. Defaults to DefaultMaxPendingRequestsPerIP. Set <=0 to disable the cap.
// contains filtered or unexported fields
}
Jaws holds the server-side state and configuration for a JaWS instance.
A single Jaws value coordinates template lookup, session handling and the request lifecycle that keeps the browser and backend synchronized via WebSockets. The zero value is not ready for use; construct instances with New to ensure the helper goroutines and static assets are prepared.
The exported configuration fields are ordinary fields, not live synchronized settings. Several are consulted on each connection or request (for example MaxPendingRequestsPerIP and WebSocketPingInterval), so set them all before exposing handlers, creating Requests, or starting Jaws.Serve / Jaws.ServeWithTimeout; mutating one after serving has begun is an unsynchronized write and is not supported. Methods document their own concurrency behavior and may be called concurrently when stated.
func New ¶
New allocates a JaWS instance with the default configuration.
The returned Jaws value is ready for use: static assets are embedded, the broadcast channels and update ticker are allocated and the request pool is primed. You must still start the processing loop with Jaws.Serve or Jaws.ServeWithTimeout on its own goroutine before broadcasting. Call Jaws.Close when finished with the instance to free associated resources.
func (*Jaws) AddTemplateLookuper ¶ added in v0.45.0
func (jw *Jaws) AddTemplateLookuper(tl TemplateLookuper) (err error)
AddTemplateLookuper adds a TemplateLookuper.
The lookuper must be comparable so it can be removed with Jaws.RemoveTemplateLookuper.
func (*Jaws) Alert ¶
Alert sends an alert to all active Request values.
The level argument should be one of Bootstrap's alert levels: primary, secondary, success, danger, warning, info, light or dark.
The level and msg are HTML-escaped before being sent, so it is safe to pass untrusted text; do not pre-escape it.
func (*Jaws) Append ¶
Append calls the JavaScript appendChild method on all HTML elements matching target.
func (*Jaws) Broadcast ¶
Broadcast sends msg to the active Request and Element values selected by wire.Message.Dest.
It must not be called before the JaWS processing loop (Jaws.Serve or Jaws.ServeWithTimeout) is running. Otherwise this call may block.
All convenience helpers on Jaws that call Broadcast inherit this requirement.
A nil wire.Message.Dest targets every active Request; a key.Key Dest targets the active Request with that identity key, and a zero key is dropped. Any other Dest is expanded into tags. Plain strings and Jid values are illegal tag types; use tag.Tag, a domain tag, or an Element method instead.
A wire.Message.Dest that cannot be expanded into tags (an illegal tag type) is reported through Jaws.MustLog, which panics when no Jaws.Logger is set; with a Logger the error is logged and the message is sent to the destinations that did expand.
func (*Jaws) Close ¶
func (jw *Jaws) Close()
Close initiates shutdown of the Jaws instance.
Jaws.Done is closed as shutdown begins. Before Close returns, the context returned by Request.Context for every current Request is canceled, including pending Requests whose WebSocket never connected. Non-running Requests become unclaimable but retain their identity while callers hold them. Active WebSocket handlers observe cancellation and finish asynchronously.
Calls to Jaws.NewRequest after shutdown begins return Requests with already-canceled contexts that Jaws.UseRequest cannot claim. Broadcasts and sends may be discarded after Done closes. Subsequent calls to Close have no effect.
func (*Jaws) ContentSecurityPolicy ¶ added in v0.300.0
ContentSecurityPolicy returns the generated Content-Security-Policy header value.
func (*Jaws) DefaultAuth ¶ added in v0.600.0
func (jw *Jaws) DefaultAuth() *DefaultAuth
DefaultAuth returns the shared fail-open DefaultAuth used for templates when Jaws.MakeAuth is nil.
It is created on first use and reused, so the sync.Once warning in DefaultAuth.IsAdmin fires at most once per Jaws rather than once per template render. The value of Jaws.Logger in effect at first use is captured.
func (*Jaws) Dirty ¶ added in v0.31.0
Dirty marks all Element values that have one or more of the given tags as dirty.
If any tag implements tag.TagGetter it is called with a nil Request; prefer Request.Dirty, which avoids this. A tag that is not hashable panics the calling goroutine, but the panic is contained there and the Jaws.Serve loop is unaffected. Request.Dirty behaves the same here.
func (*Jaws) Done ¶
func (jw *Jaws) Done() <-chan struct{}
Done returns a channel closed when Jaws.Close begins shutdown.
func (*Jaws) FaviconURL ¶ added in v0.111.6
FaviconURL returns the favicon URL discovered by Jaws.GenerateHeadHTML.
func (*Jaws) GenerateHeadHTML ¶ added in v0.5.0
GenerateHeadHTML regenerates the HTML code that goes in the HEAD section, ensuring that the provided URL resources in extra are loaded, along with the JaWS JavaScript.
If one of the resources is named "favicon", its URL will be stored and can be retrieved using Jaws.FaviconURL.
If one or more URLs in extra fail to parse, GenerateHeadHTML still installs the regenerated head HTML and Content-Security-Policy with the failing resources omitted, and returns the joined parse errors.
You only need to call this if you add your own images, scripts and stylesheets.
func (*Jaws) GetSession ¶ added in v0.11.0
GetSession returns the Session associated with the given http.Request, or nil.
Sessions are bound to the client IP (see the clientIP method). Behind a reverse proxy that connects over loopback, every request appears to come from loopback and IP binding is effectively disabled unless Jaws.TrustForwardedHeaders is enabled so the forwarded client IP is used instead.
func (*Jaws) Insert ¶
Insert inserts html before the child at childIndex in every element matching target.
target follows Jaws.Broadcast's tag rules. For request-local insertion before a known child, use Element.InsertBefore.
A negative childIndex is reported as ErrInvalidChildIndex and no message is sent. Use Jaws.Append to insert at the end. html is trusted HTML, matching Jaws.SetInner and Jaws.Append.
func (*Jaws) JsCall ¶ added in v0.114.0
JsCall calls a browser JavaScript function path for matching targets.
target selects which requests or elements receive the Call message. In each receiving browser, jsfunc is resolved as a path from window and called with JSON.parse(jsonstr); the matched element is not passed as this or as an argument. A nil target calls each active Request once. A nonzero key.Key target calls the matching active Request once without requiring a matching DOM element; a zero key is ignored. Other targets follow Jaws.Broadcast's tag rules.
func (*Jaws) Log ¶
Log sends an error to the Jaws.Logger if set. Has no effect if err is nil or the Logger is nil. Returns err.
func (*Jaws) LookupTemplate ¶ added in v0.66.0
LookupTemplate queries the known TemplateLookuper values in the order they were added and returns the first found.
func (*Jaws) MustLog ¶ added in v0.1.1
MustLog sends an error to the Jaws.Logger if set, or panics with the given error if the Logger is nil. Has no effect if err is nil.
Some update-time paths cannot return errors to their caller and report them through MustLog. Set Jaws.Logger when those errors should be logged instead of treated as fatal programming errors.
func (*Jaws) NewRequest ¶
NewRequest returns a new JaWS Request.
While the Jaws instance is open, the returned Request is pending until it is claimed or retired.
Call this as soon as you start processing an HTML request, and store the returned Request pointer so it can be used while constructing the HTML response in order to register the JaWS IDs you use in the response, and use its Request.JawsKey when sending the JavaScript portion of the reply. Do not retain the pointer beyond the initial HTTP handling and rendering; see Request.
Automatic timeout handling is performed by Jaws.ServeWithTimeout. The default Jaws.Serve helper uses a 10-second timeout.
A Request created after Jaws.Close has an already-canceled context and cannot be claimed by Jaws.UseRequest.
When timeout maintenance or the per-IP pending limit retires an unclaimed Request, its key becomes unclaimable. The key also remains unavailable for assignment to another Request while the retired Request is reachable; no deadline is guaranteed for later reuse.
NewRequest panics if the system CSPRNG (crypto/rand) fails while generating the request key, which does not happen on supported platforms.
func (*Jaws) NewSession ¶ added in v0.26.0
NewSession creates a new Session.
Any pre-existing Session will be cleared and closed. This may call Session.Close on an existing session and therefore requires the JaWS processing loop (Jaws.Serve or Jaws.ServeWithTimeout) to be running.
Subsequent Request values created with Jaws.NewRequest that have the cookie set and originate from the same IP will be able to access the Session. The IP comparison is the same loopback-aware, optionally forwarded-header-based match used everywhere else; see Jaws.GetSession and Jaws.TrustForwardedHeaders for the reverse-proxy caveat.
As a side effect, the session cookie is also added to r itself, so the new Session is visible to Jaws.GetSession and Jaws.NewRequest for the remainder of the same HTTP request.
It panics if the system CSPRNG (crypto/rand) fails while generating the session ID, which does not happen on supported platforms.
func (*Jaws) Pending ¶
Pending returns the number of requests waiting for their WebSocket callbacks.
func (*Jaws) Redirect ¶
Redirect requests all active Request values to navigate to the given URL.
The URL is validated to be a relative path or an http/https URL; script-bearing schemes such as javascript: and protocol-relative ("//host") URLs are refused and logged rather than sent to the browser.
func (*Jaws) Reload ¶
func (jw *Jaws) Reload()
Reload requests all active Request values to reload their current page.
func (*Jaws) RemoveAttr ¶
RemoveAttr sends a request to remove the given attribute from all HTML elements matching target.
func (*Jaws) RemoveClass ¶ added in v0.31.0
RemoveClass sends a request to remove the given class from all HTML elements matching target.
func (*Jaws) RemoveTemplateLookuper ¶ added in v0.45.0
func (jw *Jaws) RemoveTemplateLookuper(tl TemplateLookuper) (err error)
RemoveTemplateLookuper removes the given TemplateLookuper.
func (*Jaws) Replace ¶
Replace replaces HTML on all HTML elements matching target.
html is trusted HTML, matching Jaws.SetInner and Jaws.Append.
func (*Jaws) RequestCount ¶ added in v0.25.0
RequestCount returns the total Request count.
It equals the total returned by Jaws.RequestCounts.
func (*Jaws) RequestCounts ¶ added in v0.407.0
RequestCounts returns the total and active Request counts.
The total includes pending, claimed, and active Request values. It excludes retired Requests, even if an initial HTTP handler still holds them. The active count includes Requests whose Request.ServeHTTP loop is running.
func (*Jaws) SecureHeadersMiddleware ¶ added in v0.300.0
SecureHeadersMiddleware wraps next with security headers that match the current JaWS configuration.
It clones secureheaders.DefaultHeaders(), replacing the Content-Security-Policy value with Jaws.ContentSecurityPolicy for each request so responses allow the resources configured by Jaws.GenerateHeadHTML.
The returned middleware does not trust forwarded HTTPS headers. Note that the session cookie Secure flag is governed separately by Jaws.TrustForwardedHeaders (also false by default), so the two stay consistent unless you opt in. The next handler must be non-nil.
func (*Jaws) Serve ¶
func (jw *Jaws) Serve()
Serve calls ServeWithTimeout(DefaultWebSocketTimeout). It is intended to run on its own goroutine. It returns when Jaws.Close is called.
func (*Jaws) ServeHTTP ¶ added in v0.19.0
func (jw *Jaws) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP can handle the required JaWS endpoints, which all start with "/jaws/".
The method is checked per matched endpoint, not up front: the static asset and .ping endpoints answer GET and HEAD (any other method gets 405 with an Allow header), while the per-Request key and tail-script endpoints are GET-only capability URLs that fall through to 404 on any other method. An unknown path or a wrong method on a capability URL therefore 404s rather than 405s, and never reveals whether a key is valid.
func (*Jaws) ServeWithTimeout ¶
ServeWithTimeout begins processing requests with the given timeout. It is intended to run on its own goroutine. It returns when Jaws.Close is called.
func (*Jaws) SessionCount ¶ added in v0.11.0
SessionCount returns the number of active sessions.
func (*Jaws) SessionMiddleware ¶ added in v0.600.0
SessionMiddleware returns an http.Handler that ensures a JaWS Session exists before invoking h, creating one if the request has none.
It is the session-ensuring middleware, distinct from the session accessors: Jaws.GetSession and Request.Session look up an existing Session, while this wraps a handler. It composes with Jaws.SecureHeadersMiddleware.
func (*Jaws) Sessions ¶ added in v0.11.0
Sessions returns a list of all active sessions, which may be nil.
func (*Jaws) SetAttr ¶
SetAttr sends a request to replace the given attribute value in all HTML elements matching target.
The value parameter must be the unescaped logical attribute value. It is sent to the browser DOM and used as the value argument to setAttribute().
func (*Jaws) SetClass ¶ added in v0.31.0
SetClass sends a request to set the given class in all HTML elements matching target.
func (*Jaws) SetInner ¶
SetInner sends a request to replace the inner HTML of all HTML elements matching target.
func (*Jaws) SetValue ¶
SetValue sends a request to set the current input value (in textual form) of all HTML elements matching target. It sets the live DOM value/state, not the HTML "value" attribute.
func (*Jaws) Setup ¶ added in v0.111.6
func (jw *Jaws) Setup(handleFn HandleFunc, prefix string, extras ...any) (err error)
Setup configures Jaws with extra functionality and resources.
The list of extras can be strings, *url.URL, *staticserve.StaticServe or []*staticserve.StaticServe URL resources, or a setup function matching SetupFunc such as jawsboot.Setup.
It calls Jaws.GenerateHeadHTML with the final list of URLs, with any relative URL paths prefixed with prefix.
If handleFn is nil, Setup generates head HTML from the configured resources without registering any handlers.
func (*Jaws) TestServe ¶ added in v0.500.0
func (jw *Jaws) TestServe(rq *Request, onPanic func(recovered any)) (inCh chan wire.WsMsg, outCh chan wire.WsMsg, bcastCh chan wire.Message, readyCh, doneCh chan struct{})
TestServe runs rq's WebSocket message-processing loop for test harnesses, including the out-of-package harness in github.com/linkdata/jaws/jawstest.
It subscribes rq to broadcasts, waits for the running Serve loop to process the subscription, then runs rq.process in a new goroutine using freshly created inbound/outbound channels, recycling rq when the loop stops. It panics if the Jaws processing loop (Jaws.Serve or Jaws.ServeWithTimeout) is not running.
TestServe is exported solely to let test harnesses outside package jaws drive a request loop without access to unexported internals. It is not intended for production use; it does not import any testing-only packages, so it does not pull net/http/httptest into the production build.
onPanic must be non-nil; it is called with the recovered value (nil if the loop exited normally) when the loop goroutine stops, before doneCh is closed, so a harness can publish captured panic state before any <-doneCh waiter observes it. A harness that does not expect panics should re-panic when the value is non-nil so unexpected loop panics still surface.
func (*Jaws) UseRequest ¶
UseRequest extracts the JaWS Request with the given key from the request map if it exists and the HTTP request remote IP matches.
Call it when receiving the WebSocket connection on "/jaws/:key" to get the associated Request, and then call its Request.ServeHTTP method to process the WebSocket messages.
Returns nil if the key was not found, the request was already claimed by an earlier WebSocket callback, or the IP doesn't match, in which case you should return an HTTP "404 Not Found" status.
The returned pointer is borrowed for WebSocket handling. Do not retain it after Request.ServeHTTP returns; see Request.
type Jid ¶ added in v0.31.0
Jid is the identifier type used for HTML elements managed by JaWS.
It is provided as a convenience alias to the value defined in the jid subpackage so applications do not have to import that package directly when working with element IDs.
type Logger ¶ added in v0.110.1
type Logger interface {
Info(msg string, args ...any)
Warn(msg string, args ...any)
Error(msg string, args ...any)
}
Logger is satisfied by a *log/slog.Logger via its Info, Warn and Error methods.
type MakeAuthFn ¶ added in v0.85.0
MakeAuthFn constructs an Auth value for a Request.
Set Jaws.MakeAuth to your implementation to enforce real authorization. If Jaws.MakeAuth is left nil, templates receive DefaultAuth, which is fail-open: see its documentation.
It is a type alias so a bare func value can be assigned without conversion, matching the sibling callback types ConnectFn, InputFn and HandleFunc.
type Renderer ¶ added in v0.60.0
type Renderer interface {
// JawsRender is called once per [Element] when rendering the initial webpage.
// Do not call this yourself unless it is from within another JawsRender implementation.
// The engine does not invoke this once the [Element] is deleted (see [Element.Deleted]).
JawsRender(elem *Element, w io.Writer, params []any) error
}
Renderer renders the initial HTML for a UI object.
type Request ¶
type Request struct {
Jaws *Jaws // (read-only) the JaWS instance the Request belongs to
JawsKey key.Key // (read-only) random key assigned to this Request; routes JaWS URLs and request-targeted broadcasts only while registered
// contains filtered or unexported fields
}
Request maintains the state for a JaWS WebSocket connection, and handles processing of events and broadcasts.
A Request pointer is borrowed for the HTTP or WebSocket lifecycle that supplied it. Do not retain it in application state or use it from a background goroutine: a Request that enters Request.ServeHTTP may be returned to an internal pool when ServeHTTP returns, and the same pointer may later represent another connection. Background work should retain Request.Context and, when it must terminate the connection, the cancel function returned while deriving a replacement context through Request.SetContext.
Unlike Session, whose methods are nil-safe, Request methods are not safe to call on a nil *Request: a Request is always obtained from Jaws.NewRequest or Jaws.UseRequest and is never legitimately nil. The nil-receiver guard on Request.JawsKeyString (and thus Request.String) lets a nil Request render into error text, while those on Request.Log and Request.MustLog let it forward to the logger; both exist only for that diagnostic use, not as a public nil-safe contract.
func (*Request) Alert ¶
Alert attempts to show an alert message on the current request webpage if it has an HTML element with the data-jaws-alerts attribute.
The level argument should be one of Bootstrap's alert levels: primary, secondary, success, danger, warning, info, light or dark.
The level and msg are HTML-escaped before being sent, so it is safe to pass untrusted text; do not pre-escape it.
The default JaWS JavaScript only supports Bootstrap dismissible alerts.
See Request for pointer lifetime and Jaws.Broadcast for processing-loop requirements.
func (*Request) AlertError ¶
AlertError logs err via Jaws.Log and, if it is non-nil, also shows it to the current request as a danger-level Request.Alert.
func (*Request) Cancel ¶ added in v0.500.0
Cancel aborts the Request.
It cancels the Request's context with the given cause (logged via Jaws.Logger); the WebSocket processing loop and its goroutines observe the cancelled context and shut down asynchronously. Cancel returns immediately and does not wait for teardown. It is safe to call synchronously from UI code, for example to terminate a connection that violates a server-side limit. A nil err cancels without a specific cause.
Do not retain the Request for asynchronous cancellation; use Request.SetContext and retain the derived context's cancellation function instead.
func (*Request) Context ¶
Context returns the Request's context.
The context is derived from Jaws.BaseContext by default. Unlike the Request pointer, it may be retained by background work.
func (*Request) DeleteElement ¶ added in v0.300.0
DeleteElement removes elem from the Request element registry without queueing a browser operation.
Use Element.Remove to remove a managed DOM child and unregister it together. DeleteElement is intended for elements that were never successfully rendered, or whose DOM lifecycle is managed separately.
A nil elem is a no-op, matching Request.Tag, Request.TagExpanded and Request.TagsOf; passing the nil that Request.GetElementByJid returns for an unknown Jid is therefore safe.
func (*Request) Dirty ¶ added in v0.31.0
Dirty marks all Element values that have one or more of the given tags as dirty.
func (*Request) Get ¶ added in v0.11.0
Get is shorthand for Session.Get.
It returns the session value associated with key, or nil if no session is associated with the Request.
func (*Request) GetConnectFn ¶ added in v0.7.0
GetConnectFn returns the currently set ConnectFn. That function will be called before starting the WebSocket tunnel if not nil.
func (*Request) GetElementByJid ¶ added in v0.300.0
GetElementByJid returns the element with jid, or nil if it is not known.
func (*Request) GetElements ¶ added in v0.31.0
GetElements returns a list of the UI elements in the Request that have the given tags.
func (*Request) HeadHTML ¶
HeadHTML writes the configured resources and Request key metadata for the page head.
func (*Request) Initial ¶ added in v0.8.0
Initial returns the Request's initial HTTP request, or nil.
func (*Request) JawsKeyString ¶
JawsKeyString returns the request key in the text form used by JaWS URLs.
func (*Request) Log ¶ added in v0.300.0
Log sends an error to the Jaws.Logger if set. Has no effect if err is nil or the Logger is nil. Returns err.
func (*Request) MarkWritten ¶ added in v0.600.0
func (rq *Request) MarkWritten()
MarkWritten records that the Request's initial HTML is being written, so the pending-eviction logic spares it while a render is in flight.
[RequestWriter.Write] calls it on every write. It is lock-free and safe to call concurrently. Concurrent calls never move the recorded second backward.
func (*Request) MustLog ¶ added in v0.300.0
MustLog sends an error to the Jaws.Logger if set, or panics with the given error if the Logger is nil. Has no effect if err is nil.
Some update-time paths cannot return errors to their caller and report them through MustLog. Set Jaws.Logger when those errors should be logged instead of treated as fatal programming errors.
func (*Request) NewElement ¶ added in v0.31.0
NewElement creates a new Element using the given UI object.
The UI value becomes scoped to rq and must not be used with another Request. See UI for the ownership contract.
Panics if the build tag "debug" is set and the UI object doesn't satisfy all requirements.
func (*Request) Redirect ¶
Redirect requests the current Request to navigate to the given URL.
The URL is validated to be a relative path or an http/https URL; script-bearing schemes such as javascript: and protocol-relative ("//host") URLs are refused and logged rather than sent to the browser.
See Request for pointer lifetime and Jaws.Broadcast for processing-loop requirements.
func (*Request) ServeHTTP ¶
func (rq *Request) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements http.Handler.
Requires Jaws.UseRequest to have been successfully called for the Request. The JaWS processing loop (Jaws.Serve or Jaws.ServeWithTimeout) must also be running so the request can subscribe to broadcasts and unsubscribe on exit.
func (*Request) Set ¶ added in v0.11.0
Set is shorthand for Session.Set.
It associates value with key in the session; a nil value removes the key. It does nothing if no session is associated with the Request.
func (*Request) SetConnectFn ¶ added in v0.7.0
SetConnectFn sets the ConnectFn. That function will be called before starting the WebSocket tunnel if not nil.
func (*Request) SetContext ¶ added in v0.110.0
SetContext atomically transforms the Request's context.
fn receives the current context and must return a non-nil context derived from it so cancellation and deadlines continue to propagate. Cancellation or deadline expiration of the returned context wakes a running Request.ServeHTTP loop promptly, even while it is idle; no WebSocket event or broadcast is required.
fn runs while the Request lock is held. It must not call methods on the same Request, call code that may do so, or block on work that needs the same Request. SetContext panics if fn is nil. If fn panics, SetContext releases the lock and propagates the panic.
Background work that must cancel the Request should create a derived context in fn and retain that context's cancellation function, not the Request pointer.
Returning a nil context is a programming error: debug builds panic and production builds report it through Jaws.MustLog and retain the current context.
func (*Request) String ¶
String returns the Request in the form "Request<key>", using Request.JawsKeyString to encode the key. Like JawsKeyString it tolerates a nil receiver for diagnostics only; see the Request type documentation.
func (*Request) TagExpanded ¶ added in v0.300.0
TagExpanded adds already-expanded tags to the given Element.
func (*Request) TagsOf ¶ added in v0.31.0
TagsOf returns the tags currently associated with elem in this Request, or nil if elem is nil. The returned slice is a newly allocated snapshot and may be retained and modified by the caller.
func (*Request) TailHTML ¶ added in v0.79.0
TailHTML writes optional HTML code at the end of the page's BODY section that will immediately apply HTML attribute and class updates made during initial rendering, which minimizes flicker without having to write the correct value in templates or during Renderer.JawsRender.
It also adds a <noscript> tag that warns of reduced functionality.
type Session ¶ added in v0.11.0
type Session struct {
// contains filtered or unexported fields
}
Session stores server-side per-user state shared by one or more requests.
A Session is bound to the remote IP that created it. Its exported methods are safe to call on a nil *Session; those calls return the documented zero value or do nothing.
func (*Session) Broadcast ¶ added in v0.26.0
Broadcast attempts to send a message to all active Request values using this session.
It must not be called before the JaWS processing loop (Jaws.Serve or Jaws.ServeWithTimeout) is running. Otherwise this call may block. It is safe to call on a nil Session.
func (*Session) Clear ¶ added in v0.16.0
func (sess *Session) Clear()
Clear removes all key/value pairs from the session. It is safe to call on a nil Session.
func (*Session) Close ¶ added in v0.17.0
Close invalidates and expires the Session. Future Request values won't be able to associate with it, and Session.Cookie will return a deletion cookie.
Existing Request values already associated with the Session will ask the browser to reload the pages. Key/value pairs in the Session are left unmodified; use Session.Clear to remove all of them.
It must not be called before the JaWS processing loop (Jaws.Serve or Jaws.ServeWithTimeout) is running, because reload broadcasts may block.
Returns a cookie to be sent to the client browser that will delete the browser cookie. It is safe to call on a nil Session, in which case it returns nil; for any non-nil Session it returns a non-nil deletion cookie.
func (*Session) Cookie ¶ added in v0.11.0
Cookie returns a cookie for the Session. Returns a delete cookie if the Session is expired. It is safe to call on a nil Session, in which case it returns nil.
func (*Session) CookieValue ¶ added in v0.11.0
CookieValue returns the session cookie value. It is safe to call on a nil Session, in which case it returns an empty string.
func (*Session) Get ¶ added in v0.11.0
Get returns the value associated with the key, or nil. It is safe to call on a nil Session.
func (*Session) ID ¶ added in v0.11.0
ID returns the session ID, a 64-bit random value. It is safe to call on a nil Session, in which case it returns zero.
func (*Session) IP ¶ added in v0.11.0
IP returns the remote IP the session is bound to, or the zero netip.Addr if unset. It is safe to call on a nil Session, in which case it returns the zero netip.Addr.
func (*Session) Jaws ¶ added in v0.81.0
Jaws returns the Jaws instance of the Session, or nil. It is safe to call on a nil Session.
func (*Session) Reload ¶ added in v0.17.0
func (sess *Session) Reload()
Reload calls Session.Broadcast with a message asking browsers to reload the page. See Session.Broadcast for the processing-loop requirement. It is safe to call on a nil Session.
type SetupFunc ¶ added in v0.111.6
SetupFunc is called by Jaws.Setup and allows setting up addons for JaWS.
When Jaws.Setup is called with a nil HandleFunc, setup functions receive a no-op handler registration function.
The URLs returned will be used in a call to Jaws.GenerateHeadHTML.
type TemplateLookuper ¶ added in v0.45.0
TemplateLookuper resolves a name to a *template.Template.
type UI ¶ added in v0.31.0
UI defines the required methods on JaWS UI objects.
A UI value is request-scoped. Once it has been used to create an Element for one Request, it must not be used to create an Element for another Request. Construct a fresh UI value for each Request. The application state, getters, setters, handlers and tags referenced by those UI values may be shared across Requests when synchronized as required.
In addition, all UI objects must be comparable so they can be used as map keys. The compile-time type must be comparable; debug builds additionally perform a runtime value-level check in Request.NewElement and panic on a value that is statically comparable but not comparable at runtime (for example a comparable struct holding a func in an interface field). Production builds rely on the static check alone, so such a value is accepted and instead panics when first used as a map key; callers must therefore ensure UI values are genuinely comparable.
type Updater ¶ added in v0.60.0
type Updater interface {
// JawsUpdate is called for an [Element] that has been marked dirty to update its HTML.
// Do not call this yourself unless it is from within another JawsUpdate implementation.
// The engine does not invoke this once the [Element] is deleted (see [Element.Deleted]).
JawsUpdate(elem *Element)
}
Updater updates browser-side DOM for a dirty Element.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package examples contains compile-checked examples for JaWS applications.
|
Package examples contains compile-checked examples for JaWS applications. |
|
minesweeper
command
Package main implements the JaWS Minesweeper demo.
|
Package main implements the JaWS Minesweeper demo. |
|
Package jawsboot provides embedded Bootstrap assets for JaWS applications.
|
Package jawsboot provides embedded Bootstrap assets for JaWS applications. |
|
Package jawstest provides an importable harness for driving a jaws.Request's WebSocket message-processing loop in tests.
|
Package jawstest provides an importable harness for driving a jaws.Request's WebSocket message-processing loop in tests. |
|
lib
|
|
|
assets
Package assets contains the embedded client assets and helpers used by JaWS setup code.
|
Package assets contains the embedded client assets and helpers used by JaWS setup code. |
|
bind
Package bind adapts Go values to JaWS getter, setter, HTML and tag interfaces.
|
Package bind adapts Go values to JaWS getter, setter, HTML and tag interfaces. |
|
htmlio
Package htmlio writes the small HTML fragments used by standard JaWS widgets.
|
Package htmlio writes the small HTML fragments used by standard JaWS widgets. |
|
jid
Package jid provides JaWS element identifiers and helpers for writing them into HTML.
|
Package jid provides JaWS element identifiers and helpers for writing them into HTML. |
|
key
Package key implements JaWS key encoding.
|
Package key implements JaWS key encoding. |
|
named
Package named provides named boolean values and collections used by select, option and radio widgets.
|
Package named provides named boolean values and collections used by select, option and radio widgets. |
|
tag
Package tag expands JaWS tag values into comparable keys that identify elements during dirtying, broadcasts and event routing.
|
Package tag expands JaWS tag values into comparable keys that identify elements during dirtying, broadcasts and event routing. |
|
templatereloader
Package templatereloader provides a jaws.TemplateLookuper that reparses templates from disk while running in debug or race builds.
|
Package templatereloader provides a jaws.TemplateLookuper that reparses templates from disk while running in debug or race builds. |
|
ui
Package ui contains the standard JaWS widget implementations.
|
Package ui contains the standard JaWS widget implementations. |
|
what
Package what defines the commands and events used by the JaWS wire protocol.
|
Package what defines the commands and events used by the JaWS wire protocol. |
|
wire
Package wire formats and parses the line-based JaWS WebSocket protocol.
|
Package wire formats and parses the line-based JaWS WebSocket protocol. |