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 ServeHTTP interface.
Index ¶
- Constants
- Variables
- func AppendID(b []byte) []byte
- func CallEventHandlers(ui any, e *Element, wht what.What, val string) (err error)
- func MakeID() string
- func NextID() int64
- type Auth
- type ClickHandler
- type ConnectFn
- type Container
- type DefaultAuth
- type Element
- func (e *Element) AddHandlers(h ...EventHandler)
- func (e *Element) Append(htmlCode template.HTML)
- func (e *Element) ApplyGetter(getter any) (tag any, err error)
- func (e *Element) ApplyParams(params []any) (retv []template.HTMLAttr)
- func (e *Element) HasTag(tag any) bool
- func (e *Element) JawsRender(w io.Writer, params []any) (err error)
- func (e *Element) JawsUpdate()
- func (e *Element) Jid() jid.Jid
- func (e *Element) Order(jidList []jid.Jid)
- func (e *Element) Remove(htmlId string)
- func (e *Element) RemoveAttr(attr string)
- func (e *Element) RemoveClass(cls string)
- func (e *Element) Replace(htmlCode template.HTML)
- func (e *Element) SetAttr(attr, val string)
- func (e *Element) SetClass(cls string)
- func (e *Element) SetInner(innerHTML template.HTML)
- func (e *Element) SetValue(val string)
- func (e *Element) String() string
- func (e *Element) Tag(tags ...any)
- func (e *Element) Ui() UI
- type EventFn
- type EventHandler
- type HandleFunc
- type InitHandler
- type Jaws
- func (jw *Jaws) AddTemplateLookuper(tl TemplateLookuper) (err error)
- func (jw *Jaws) Alert(lvl, 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) 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(hr *http.Request) (sess *Session)
- func (jw *Jaws) Insert(target any, where, html string)
- func (jw *Jaws) JsCall(tag 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(hr *http.Request) (rq *Request)
- func (jw *Jaws) NewSession(w http.ResponseWriter, hr *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 string)
- func (jw *Jaws) RequestCount() (n 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) Session(h http.Handler) http.Handler
- func (jw *Jaws) SessionCount() (n int)
- func (jw *Jaws) Sessions() (sl []*Session)
- func (jw *Jaws) SetAttr(target any, attr, val string)
- func (jw *Jaws) SetClass(target any, cls string)
- func (jw *Jaws) SetInner(target any, innerHTML template.HTML)
- func (jw *Jaws) SetValue(target any, val string)
- func (jw *Jaws) Setup(handleFn HandleFunc, prefix string, extras ...any) (err error)
- func (jw *Jaws) UseRequest(jawsKey uint64, hr *http.Request) (rq *Request)
- type Jid
- type Logger
- type MakeAuthFn
- type Renderer
- type Request
- func (rq *Request) Alert(lvl, msg string)
- func (rq *Request) AlertError(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) (e *Element)
- func (rq *Request) GetElements(tagitem any) (elems []*Element)
- func (rq *Request) HasTag(elem *Element, tag 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) 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, val 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) (val 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() (rl []*Request)
- func (sess *Session) Set(key string, val any)
- type SetupFunc
- type TemplateLookuper
- type TestRequest
- type UI
- type Updater
Constants ¶
const ( DefaultUpdateInterval = time.Millisecond * 100 // Default browser update interval DefaultWebSocketPingInterval = time.Minute // Default WebSocket keepalive ping interval DefaultWebSocketTimeout = time.Second * 10 // WebSocket must connect and respond within this interval )
Variables ¶
var ( ErrWebsocketOriginMissing = errors.New("websocket request missing Origin header") ErrWebsocketOriginWrongScheme = errors.New("websocket Origin not http or https") ErrWebsocketOriginWrongHost = errors.New("websocket Origin host mismatch") ErrRequestAlreadyClaimed = errors.New("request already claimed") ErrJavascriptDisabled = errors.New("javascript is disabled") )
var ErrEventHandlerPanic errEventHandlerPanic
ErrEventHandlerPanic is returned when an event handler panics.
var ErrEventUnhandled = errEventUnhandled{}
ErrEventUnhandled returned by JawsEvent() or JawsClick() causes the next available handler to be invoked.
var ErrNoWebSocketRequest errNoWebSocketRequest
ErrNoWebSocketRequest is returned when the WebSocket callback was not received within the timeout period. Most common reason is that client is not using Javascript.
var ErrRequestCancelled errRequestCancelled
ErrRequestCancelled indicates a Request was cancelled. Use Unwrap() to see the underlying cause.
var ErrValueUnchanged = errors.New("value unchanged")
ErrValueUnchanged can be returned from JawsSet[Type] functions to indicate that while there was no error, the underlying value was already the desired value.
Functions ¶
func AppendID ¶ added in v0.31.0
AppendID appends the result of NextID() in text form to the given slice.
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.
Types ¶
type ClickHandler ¶ added in v0.31.0
type ClickHandler interface {
// JawsClick is called when an Element's HTML element or something within it
// is clicked in the browser.
//
// The name parameter is taken from the first 'name' HTML attribute or HTML
// 'button' textContent found when traversing the DOM. It may be empty.
JawsClick(e *Element, name string) (err error)
}
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 DefaultAuth ¶ added in v0.300.0
type DefaultAuth struct{}
func (DefaultAuth) Data ¶ added in v0.300.0
func (DefaultAuth) Data() map[string]any
func (DefaultAuth) Email ¶ added in v0.300.0
func (DefaultAuth) Email() string
func (DefaultAuth) IsAdmin ¶ added in v0.300.0
func (DefaultAuth) IsAdmin() bool
type Element ¶ added in v0.31.0
type Element struct {
*Request // (read-only) the Request the Element belongs to
// contains filtered or unexported fields
}
An Element is an instance of a *Request, an UI object and a Jid.
func (*Element) AddHandlers ¶ added in v0.300.0
func (e *Element) AddHandlers(h ...EventHandler)
AddHandler adds the given handlers to the Element.
func (*Element) Append ¶ added in v0.31.0
Append appends a new HTML element as a child to the current one.
Call this only during JawsRender() or JawsUpdate() processing.
func (*Element) ApplyGetter ¶ added in v0.75.0
ApplyGetter examines getter, and if it's not nil, either adds it as a Tag, or, if it is a TagGetter, adds the result of that as a Tag.
If getter is a ClickHandler or an EventHandler, it's added to the list of handlers for the Element.
Finally, if getter is an InitHandler, it's JawsInit() function is called.
Returns the Tag(s) added, or nil if getter was nil, along with any error returned from JawsInit() if it was called.
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.
func (*Element) JawsRender ¶ added in v0.55.0
JawsRender calls Ui().JawsRender() for this Element.
Do not call this yourself unless it's from within another JawsRender implementation.
func (*Element) JawsUpdate ¶ added in v0.55.0
func (e *Element) JawsUpdate()
JawsUpdate calls Ui().JawsUpdate() for this Element.
Do not call this yourself unless it's from within another JawsUpdate implementation.
func (*Element) Jid ¶ added in v0.31.0
Jid returns the JaWS ID for this Element, unique within it's Request.
func (*Element) Order ¶ added in v0.31.0
Order reorders the HTML elements.
Call this only during JawsRender() or JawsUpdate() processing.
func (*Element) Remove ¶ added in v0.31.0
Remove requests that the HTML child with the given HTML ID of this Element is removed from the Request and it's HTML element from the browser.
Call this only during JawsRender() or JawsUpdate() processing.
func (*Element) RemoveAttr ¶ added in v0.31.0
RemoveAttr queues sending a request to remove an attribute to the browser for the Element with the given JaWS ID in this Request.
Call this only during JawsRender() or JawsUpdate() processing.
func (*Element) RemoveClass ¶ added in v0.31.0
RemoveClass queues sending a request to remove a class to the browser for the Element with the given JaWS ID in this Request.
Call this only during JawsRender() or JawsUpdate() processing.
func (*Element) Replace ¶ added in v0.31.0
Replace replaces the elements entire HTML DOM node with new HTML code. If the HTML code doesn't seem to contain correct HTML ID, it panics.
Call this only during JawsRender() or JawsUpdate() processing.
func (*Element) SetAttr ¶ added in v0.31.0
SetAttr queues sending a new attribute value to the browser for the Element with the given JaWS ID in this Request.
Call this only during JawsRender() or JawsUpdate() processing.
func (*Element) SetClass ¶ added in v0.31.0
SetClass a queues sending a class to the browser for the Element with the given JaWS ID in this Request.
Call this only during JawsRender() or JawsUpdate() processing.
func (*Element) SetInner ¶ added in v0.31.0
SetInner queues sending a new inner HTML content to the browser for the Element.
Call this only during JawsRender() or JawsUpdate() processing.
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 with the given JaWS ID in this Request.
Call this only during JawsRender() or JawsUpdate() processing.
type EventFn ¶
EventFn is the signature of a event handling function to be called when JaWS receives an event message from the Javascript via the WebSocket connection.
type EventHandler ¶ added in v0.31.0
func ParseParams ¶ added in v0.60.0
func ParseParams(params []any) (tags []any, handlers []EventHandler, attrs []string)
ParseParams parses the parameters passed to UI() when creating a new Element, returning UI tags, event handlers and HTML attributes.
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, Element.Context or Element.Session.
type Jaws ¶
type Jaws struct {
CookieName string // Name for session cookies, defaults to "jaws"
Logger Logger // Optional logger to use
Debug bool // Set to true to enable debug info in generated HTML code
MakeAuth MakeAuthFn // Optional function to create With.Auth for Templates
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.
// 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.
func New ¶
New allocates a JaWS instance with the default configuration.
The returned Jaws value is ready for use: static assets are embedded, internal goroutines are configured and the request pool is primed. Call Close when the instance is no longer needed to free associated resources.
func (*Jaws) AddTemplateLookuper ¶ added in v0.45.0
func (jw *Jaws) AddTemplateLookuper(tl TemplateLookuper) (err error)
AddTemplateLookuper adds an object that can resolve strings to *template.Template.
func (*Jaws) Alert ¶
Alert sends an alert to all Requests. The lvl argument should be one of Bootstraps alert levels: primary, secondary, success, danger, warning, info, light or dark.
func (*Jaws) Append ¶
Append calls the Javascript 'appendChild()' method on all HTML elements matching target.
func (*Jaws) Broadcast ¶
Broadcast sends a message to all Requests.
It must not be called before the JaWS processing loop (`Serve()` or `ServeWithTimeout()`) is running. Otherwise this call may block once the internal broadcast channel fills.
All convenience helpers on Jaws that call Broadcast inherit this requirement.
func (*Jaws) Close ¶
func (jw *Jaws) Close()
Close frees resources associated with the JaWS object, and closes the completion channel if the JaWS was created with New(). Once the completion channel is closed, broadcasts and sends may be discarded. 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) Dirty ¶ added in v0.31.0
Dirty marks all Elements that have one or more of the given tags as dirty.
Note that if any of the tags are a TagGetter, it will be called with a nil Request. Prefer using Request.Dirty() which avoids this.
func (*Jaws) Done ¶
func (jw *Jaws) Done() <-chan struct{}
Done returns the channel that is closed when Close has been called.
func (*Jaws) FaviconURL ¶ added in v0.111.6
func (*Jaws) GenerateHeadHTML ¶ added in v0.5.0
GenerateHeadHTML (re-)generates 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", it's URL will be stored and can be retrieved using FaviconURL().
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.
func (*Jaws) Insert ¶
Insert calls the Javascript 'insertBefore()' method on all HTML elements matching target.
The position parameter 'where' may be either a HTML ID, an child index or the text 'null'.
func (*Jaws) JsCall ¶ added in v0.114.0
JsCall calls the Javascript function 'jsfunc' with the argument 'jsonstr' on all Requests that have the target UI tag.
func (*Jaws) Log ¶
Log sends an error to the Logger set in the Jaws. Has no effect if the err is nil or the Logger is nil. Returns err.
func (*Jaws) LookupTemplate ¶ added in v0.66.0
LookupTemplate queries the known TemplateLookupers 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 Logger set in the Jaws or panics with the given error if no Logger is set. Has no effect if the err is nil.
func (*Jaws) NewRequest ¶
NewRequest returns a new pending JaWS request.
Call this as soon as you start processing a HTML request, and store the returned Request pointer so it can be used while constructing the HTML response in order to register the JaWS id's you use in the response, and use it's Key attribute when sending the Javascript portion of the reply.
Automatic timeout handling is performed by ServeWithTimeout. The default Serve() helper uses a 10-second timeout.
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 (`Serve()` or `ServeWithTimeout()`) to be running.
Subsequent Requests created with `NewRequest()` that have the cookie set and originates from the same IP will be able to access the Session.
func (*Jaws) Pending ¶
Pending returns the number of requests waiting for their WebSocket callbacks.
func (*Jaws) Reload ¶
func (jw *Jaws) Reload()
Reload requests all Requests 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 object from the list of TemplateLookupers.
func (*Jaws) RequestCount ¶ added in v0.25.0
RequestCount returns the number of Requests.
The count includes all Requests, including those being rendered, those waiting for the WebSocket callback and those active.
func (*Jaws) SecureHeadersMiddleware ¶ added in v0.300.0
SecureHeadersMiddleware wraps next with security headers that match the current JaWS configuration.
It snapshots secureheaders.DefaultHeaders, replacing the Content-Security-Policy value with ContentSecurityPolicy so responses allow the resources configured by GenerateHeadHTML.
The returned middleware does not trust forwarded HTTPS headers. The next handler must be non-nil.
func (*Jaws) Serve ¶
func (jw *Jaws) Serve()
Serve calls ServeWithTimeout(DefaultWebSocketTimeout). It is intended to run on it's own goroutine. It returns when 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/".
func (*Jaws) ServeWithTimeout ¶
ServeWithTimeout begins processing requests with the given timeout. It is intended to run on it's own goroutine. It returns when Close is called.
func (*Jaws) Session ¶ added in v0.77.0
Session returns a http.Handler that ensures a JaWS Session exists before invoking h.
func (*Jaws) SessionCount ¶ added in v0.11.0
SessionCount returns the number of active sessions.
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.
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 HTML "value" attribute of all HTML elements matching target.
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 or *staticserve.StaticServe (URL resources) or a setup function matching SetupFunc such as jawsboot.Setup.
It calls GenerateHeadHTML with the final list of URLs, with any relative URL paths prefixed with prefix.
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 it's ServeHTTP method to process the WebSocket messages.
Returns nil if the key was not found or the IP doesn't match, in which case you should return a HTTP "404 Not Found" status.
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.
var NextJid Jid
NextJid is the next Jid that should be used. Used when testing. Do not modify it outside of tests.
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 matches the log/slog.Logger interface.
type MakeAuthFn ¶ added in v0.85.0
type Request ¶
type Request struct {
Jaws *Jaws // (read-only) the JaWS instance the Request belongs to
JawsKey uint64 // (read-only) a random number used in the WebSocket URI to identify this Request
Rendering atomic.Bool // set to true by RequestWriter.Write()
// contains filtered or unexported fields
}
Request maintains the state for a JaWS WebSocket connection, and handles processing of events and broadcasts.
Note that we have to store the context inside the struct because there is no call chain between the Request being created and it being used once the WebSocket is created.
func (*Request) Alert ¶
Alert attempts to show an alert message on the current request webpage if it has an HTML element with the id 'jaws-alert'. The lvl argument should be one of Bootstraps alert levels: primary, secondary, success, danger, warning, info, light or dark.
The default JaWS javascript only supports Bootstrap.js dismissable alerts. See Jaws.Broadcast for processing-loop requirements.
func (*Request) AlertError ¶
AlertError calls Alert if the given error is not nil.
func (*Request) Context ¶
Context returns the Request's Context, which is by default derived from jaws.BaseContext.
func (*Request) DeleteElement ¶ added in v0.300.0
DeleteElement removes elem from the Request element registry.
This is primarily intended for UI implementations that manage dynamic child element sets and need to drop stale elements after issuing a corresponding DOM remove operation.
func (*Request) Dirty ¶ added in v0.31.0
Dirty marks all Elements 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()` and returns the session value associated with the key, or nil. It no session is associated with the Request, returns nil.
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
func (*Request) GetElements ¶ added in v0.31.0
GetElements returns a list of the UI elements in the Request that have the given tag(s).
func (*Request) Initial ¶ added in v0.8.0
Initial returns the Request's initial HTTP request, or nil.
func (*Request) JawsKeyString ¶
func (*Request) Log ¶ added in v0.300.0
Log sends an error to the Logger set in the Jaws. Has no effect if the err is nil or the Logger is nil. Returns err.
func (*Request) MustLog ¶ added in v0.300.0
MustLog sends an error to the Logger set in the Jaws or panics with the given error if no Logger is set. Has no effect if the err is nil.
func (*Request) NewElement ¶ added in v0.31.0
NewElement creates a new Element using the given UI object.
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. See Jaws.Broadcast for processing-loop requirements.
func (*Request) ServeHTTP ¶
func (rq *Request) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements http.HanderFunc.
Requires UseRequest() have been successfully called for the Request.
func (*Request) Set ¶ added in v0.11.0
Set is shorthand for `Session().Set()` and sets a session value to be associated with the key. If value is nil, the key is removed from the session. Does nothing if there is no session is associated with the Request.
func (*Request) SetConnectFn ¶ added in v0.7.0
SetConnectFn sets ConnectFn. That function will be called before starting the WebSocket tunnel if not nil.
func (*Request) SetContext ¶ added in v0.110.0
SetContext atomically replaces the Request's context with the function return value. The function is given the current context and must return a non-nil context. The returned context must be derived from oldctx so cancellation and deadlines continue to propagate to Request.Context().
func (*Request) TagExpanded ¶ added in v0.300.0
Tag adds the given tags to the given Element.
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 JawsRender().
It also adds a <noscript> tag that warns of reduces functionality.
type Session ¶ added in v0.11.0
type Session struct {
// contains filtered or unexported fields
}
func (*Session) Broadcast ¶ added in v0.26.0
Broadcast attempts to send a message to all Requests using this session.
It must not be called before the JaWS processing loop (`Serve()` or `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 Requests won't be able to associate with it, and Cookie() will return a deletion cookie.
Existing Requests already associated with the Session will ask the browser to reload the pages. Key/value pairs in the Session are left unmodified, you can use `Session.Clear()` to remove all of them.
It must not be called before the JaWS processing loop (`Serve()` or `ServeWithTimeout()`) is running, because reload broadcasts may block.
Returns a cookie to be sent to the client browser that will delete the browser cookie. Returns nil if the session was not found. It is safe to call on a nil Session.
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 (which may be nil). It is safe to call on a nil Session, in which case it returns nil.
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 Broadcast with a message asking browsers to reload the page. See Broadcast for the processing-loop requirement.
type SetupFunc ¶ added in v0.111.6
SetupFunc is called by Setup and allows setting up addons for JaWS.
The urls returned will be used in a call to GenerateHeadHTML.
type TemplateLookuper ¶ added in v0.45.0
TemplateLookuper resolves a name to a *template.Template.
type TestRequest ¶ added in v0.300.0
type TestRequest struct {
*Request
// contains filtered or unexported fields
}
TestRequest is a request harness intended for tests.
func NewTestRequest ¶ added in v0.300.0
func NewTestRequest(jw *Jaws, hr *http.Request) (tr *TestRequest)
NewTestRequest creates a TestRequest for use when testing. Passing nil for hr creates a GET / request with no body.
func (TestRequest) BodyString ¶ added in v0.300.0
func (rh TestRequest) BodyString() string