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 CastFloat64(i int) float64
- func CastInt(f float64) int
- func HeadHTML(js []string, css []string) template.HTML
- func HtmlInner(id, tag, typ, inner string, attrs ...string) template.HTML
- func HtmlInput(id, typ, val string, attrs ...string) template.HTML
- func HtmlSelect(jid string, val *NamedBoolArray, attrs ...string) template.HTML
- func JawsKeyString(jawsKey uint64) string
- func JawsKeyValue(jawsKey string) uint64
- type ClickFn
- type ConnectFn
- type EventFn
- type InputBoolFn
- type InputDateFn
- type InputFloatFn
- type InputTextFn
- type Jaws
- func (jw *Jaws) Alert(lvl, msg string)
- func (jw *Jaws) Append(parentId, html string)
- func (jw *Jaws) Broadcast(msg *Message)
- func (jw *Jaws) Close()
- func (jw *Jaws) Done() <-chan struct{}
- func (jw *Jaws) EnsureSession(hr *http.Request, minAge, maxAge int) (sess *Session, cookie *http.Cookie)
- func (jw *Jaws) GenerateHeadHTML(extra ...string) error
- func (jw *Jaws) GetSession(hr *http.Request) (sess *Session)
- func (jw *Jaws) Insert(parentId, where, html string)
- func (jw *Jaws) Log(err error) error
- func (jw *Jaws) MakeID() string
- func (jw *Jaws) MustLog(err error)
- func (jw *Jaws) NewRequest(ctx context.Context, hr *http.Request) (rq *Request)
- func (jw *Jaws) Pending() (n int)
- func (jw *Jaws) Redirect(url string)
- func (jw *Jaws) Reload()
- func (jw *Jaws) Remove(jid string)
- func (jw *Jaws) RemoveAttr(id, attr string)
- func (jw *Jaws) Replace(id, where, html string)
- 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) Sessions() (sl []*Session)
- func (jw *Jaws) SetAttr(id, attr, val string)
- func (jw *Jaws) SetInner(jid string, innerHtml string)
- func (jw *Jaws) SetValue(id, val string)
- func (jw *Jaws) Trigger(id, val string)
- func (jw *Jaws) UseRequest(jawsKey uint64, hr *http.Request) (rq *Request)
- type Message
- type NamedBool
- type NamedBoolArray
- type Request
- func (rq *Request) A(jid, inner string, fn ClickFn, attrs ...string) template.HTML
- func (rq *Request) Alert(lvl, msg string)
- func (rq *Request) AlertError(err error)
- func (rq *Request) Broadcast(msg *Message)
- func (rq *Request) Button(jid, txt string, fn ClickFn, attrs ...string) template.HTML
- func (rq *Request) Checkbox(jid string, val bool, fn InputBoolFn, attrs ...string) template.HTML
- func (rq *Request) Date(jid string, val time.Time, fn InputDateFn, attrs ...string) template.HTML
- func (rq *Request) Div(jid, inner string, fn ClickFn, attrs ...string) template.HTML
- func (rq *Request) Get(key string) interface{}
- func (rq *Request) GetConnectFn() (fn ConnectFn)
- func (rq *Request) GetEventFn(jid string) (fn EventFn, ok bool)
- func (rq *Request) HeadHTML() template.HTML
- func (rq *Request) JawsKeyString() string
- func (rq *Request) Li(jid, inner string, fn ClickFn, attrs ...string) template.HTML
- func (rq *Request) Number(jid string, val float64, fn InputFloatFn, attrs ...string) template.HTML
- func (rq *Request) OnClick(jid string, fn ClickFn) error
- func (rq *Request) OnEvent(jid string, fn EventFn) error
- func (rq *Request) OnInput(jid string, fn InputTextFn) error
- func (rq *Request) OnTrigger(jid string, fn ClickFn) error
- func (rq *Request) Password(jid string, fn InputTextFn, attrs ...string) template.HTML
- func (rq *Request) Radio(jid string, val bool, fn InputBoolFn, attrs ...string) template.HTML
- func (rq *Request) Range(jid string, val float64, fn InputFloatFn, attrs ...string) template.HTML
- func (rq *Request) Redirect(url string)
- func (rq *Request) Register(jid string) string
- func (rq *Request) RegisterEventFn(jid string, fn EventFn) string
- func (rq *Request) RemoveAttr(jid, attr string)
- func (rq *Request) Select(jid string, val *NamedBoolArray, fn InputTextFn, attrs ...string) template.HTML
- func (rq *Request) Send(msg *Message) bool
- func (rq *Request) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (rq *Request) Session() *Session
- func (rq *Request) Set(key string, val interface{})
- func (rq *Request) SetAttr(jid, attr, val string)
- func (rq *Request) SetBoolValue(jid string, val bool)
- func (rq *Request) SetConnectFn(fn ConnectFn)
- func (rq *Request) SetDateValue(jid string, val time.Time)
- func (rq *Request) SetEventFn(jid string, fn EventFn)
- func (rq *Request) SetFloatValue(jid string, val float64)
- func (rq *Request) SetInner(jid string, innerHtml string)
- func (rq *Request) SetTextValue(jid, val string)
- func (rq *Request) Span(jid, inner string, fn ClickFn, attrs ...string) template.HTML
- func (rq *Request) String() string
- func (rq *Request) Td(jid, inner string, fn ClickFn, attrs ...string) template.HTML
- func (rq *Request) Text(jid, val string, fn InputTextFn, attrs ...string) template.HTML
- func (rq *Request) Trigger(id, val string)
- func (rq *Request) Ui(elem Ui, attrs ...string) template.HTML
- type Session
- func (sess *Session) Clear()
- func (sess *Session) Close() (cookie *http.Cookie)
- func (sess *Session) Cookie() (cookie *http.Cookie)
- func (sess *Session) CookieValue() (val string)
- func (sess *Session) Get(key string) (val interface{})
- func (sess *Session) GetExpires() (when time.Time)
- func (sess *Session) ID() (id uint64)
- func (sess *Session) IP() (ip net.IP)
- func (sess *Session) Refresh(minAge, maxAge int) (cookie *http.Cookie)
- func (sess *Session) Reload()
- func (sess *Session) Set(key string, val interface{})
- func (sess *Session) SetExpires(when time.Time)
- type Ui
Constants ¶
const CookieNameDefault = "jaws"
const ISO8601 = "2006-01-02"
Variables ¶
var FuncMap = template.FuncMap{ "int": CastInt, "float64": CastFloat64, }
var JavascriptGZip = makeJavascriptGZip()
JavascriptGZip is the embedded Javascript library GZipped.
var JavascriptPath = makeJavascriptPath()
JavascriptPath is the path for the embedded JaWS Javascript library.
var JavascriptText []byte
JavascriptText is the source code for the client-side JaWS Javascript library.
Functions ¶
func CastFloat64 ¶
func HtmlSelect ¶ added in v0.2.13
func HtmlSelect(jid string, val *NamedBoolArray, attrs ...string) template.HTML
func JawsKeyString ¶
JawsKeyString returns the string to be used for the given JaWS key.
func JawsKeyValue ¶ added in v0.11.0
JawsKeyValue parses a key string (as returned JawsKeyString) into a uint64.
Types ¶
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 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 InputBoolFn ¶
type InputFloatFn ¶
type InputTextFn ¶
type Jaws ¶
type Jaws struct { CookieName string // Name for session cookies, defaults to "jaws" Logger *log.Logger // If not nil, send debug info and errors here // contains filtered or unexported fields }
func New ¶
func New() (jw *Jaws)
New returns a new JaWS object that must be closed using Close(). This is expected to be created once per HTTP server and handles publishing HTML changes across all connections.
func NewWithDone ¶
func NewWithDone(doneCh <-chan struct{}) *Jaws
NewWithDone returns a new JaWS object using the given completion channel. This is expected to be created once per HTTP server and handles publishing HTML changes across all connections.
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 the given element on all Requests.
Only the requests that have registered the ID (either with Register or OnEvent) will be sent the message.
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 are discarded. Subsequent calls to Close() have no effect.
func (*Jaws) EnsureSession ¶ added in v0.14.0
func (jw *Jaws) EnsureSession(hr *http.Request, minAge, maxAge int) (sess *Session, cookie *http.Cookie)
EnsureSession ensures a session exists with an expiry least `minAge` seconds in the future. Returns the session and optionally a session cookie to be set if a new session was created or if it's expiry time was updated.
Subsequent Requests created with `NewRequest()` that have the cookie set and originates from the same IP will be able to access the Session.
If a new session was created, the session cookie is added to `hr` so you can call `NewRequest()` with `hr` immediately. You still need to set the cookie in the response.
func (*Jaws) GenerateHeadHTML ¶ added in v0.5.0
GenerateHeadHTML (re-)generates the HTML code that goes in the HEAD section, ensuring that the provided scripts and stylesheets in `extra` are loaded.
You only need to call this if you want to add your own scripts and stylesheets.
func (*Jaws) GetSession ¶ added in v0.11.0
GetSession retrieves the session associated with the given cookie value and remote address, or nil.
func (*Jaws) Insert ¶
Insert calls the Javascript 'insertBefore()' method on the given element on all Requests. The position parameter 'where' may be either a HTML ID, an child index or the text 'null'.
Only the requests that have registered the ID (either with Register or OnEvent) will be sent the message.
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) MakeID ¶
MakeID returns a string in the form 'jaws.X' where X is a string unique within the Jaws lifetime.
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 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 with GetBodyFooter.
Don't use the http.Request's Context, as that will expire before the WebSocket call comes in.
func (*Jaws) Reload ¶
func (jw *Jaws) Reload()
Reload requests all Requests to reload their current page.
func (*Jaws) Remove ¶
Remove removes the HTML element(s) with the given 'jid' on all Requests.
Only the requests that have registered the 'jid' (either with Register or OnEvent) will be sent the message.
func (*Jaws) RemoveAttr ¶
RemoveAttr removes a given attribute from the HTML id for all Requests.
Only the requests that have registered the ID (either with Register or OnEvent) will be sent the message.
func (*Jaws) Replace ¶
Replace calls the Javascript 'replaceChild()' method on the given element on all Requests. The position parameter 'where' may be either a HTML ID or an index.
Only the requests that have registered the ID (either with Register or OnEvent) will be sent the message.
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 the completion channel is closed.
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 an HTML id and new attribute value to all Requests. If the value is an empty string, a value-less attribute will be added (such as "disabled")
Only the requests that have registered the ID (either with Register or OnEvent) will be sent the message.
func (*Jaws) SetInner ¶
SetInner sends a jid and new inner HTML to all Requests.
Only the requests that have registered the 'jid' (either with Register or OnEvent) will be sent the message.
func (*Jaws) SetValue ¶
SetValue sends an HTML id and new input value to all Requests.
Only the requests that have registered the ID (either with Register or OnEvent) will be sent the message.
func (*Jaws) Trigger ¶
Trigger invokes the event handler for the given ID with a 'trigger' event on all Requests.
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 Message ¶
type Message struct { Elem string // HTML 'jid' attribute or command (e.g. ' alert' or 'myButtonId') What string // what to change or do, (e.g. 'inner') Data string // data (e.g. inner HTML content) // contains filtered or unexported fields }
Message contains the elements of a message to be sent to Requests.
type NamedBool ¶
NamedBool stores the data required to support HTML 'select' elements and sets of HTML radio buttons.
type NamedBoolArray ¶
type NamedBoolArray []*NamedBool
NamedBoolArray is an array of pointers to NamedBool.
func NewNamedBoolArray ¶
func NewNamedBoolArray() *NamedBoolArray
NewNamedBoolArray allocates an array of *NamedBool and returns a pointer to it.
func (*NamedBoolArray) Add ¶
func (nb *NamedBoolArray) Add(val, text string)
Add creates a new NamedBool and appends it's pointer to the NamedBoolArray.
func (*NamedBoolArray) Check ¶
func (nb *NamedBoolArray) Check(val string)
Check sets all NamedBool's Checked to true in the NamedBoolArray that have the given Value.
func (*NamedBoolArray) Set ¶
func (nb *NamedBoolArray) Set(val string, state bool)
Set sets all NamedBool's Checked to state in the NamedBoolArray that have the given Value.
func (*NamedBoolArray) String ¶
func (nb *NamedBoolArray) String() string
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 Created time.Time // (read-only) when the Request was created, used for automatic cleanup Initial *http.Request // (read-only) initial HTTP request passed to Jaws.NewRequest Context context.Context // (read-only) context passed to Jaws.NewRequest // 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.
func (*Request) AlertError ¶
AlertError calls Alert if the given error is not nil.
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) GetEventFn ¶
GetEventFn checks if a given HTML element is registered and returns the it's event function (or nil) along with a boolean indicating if it's a registered ID.
func (*Request) HeadHTML ¶
HeadHTML returns the HTML code needed to write in the HTML page's HEAD section.
func (*Request) JawsKeyString ¶
func (*Request) OnClick ¶
OnClick registers a jid and a function to be called when it's click event fires. Returns a nil error so it can be used inside templates.
func (*Request) OnEvent ¶
OnEvent calls SetEventFn. Returns a nil error so it can be used inside templates.
func (*Request) OnInput ¶
func (rq *Request) OnInput(jid string, fn InputTextFn) error
OnInput registers a jid and a function to be called when it's input event fires. Returns a nil error so it can be used inside templates.
func (*Request) OnTrigger ¶ added in v0.6.0
OnTrigger registers a jid and a function to be called when Trigger is called for it. Returns a nil error so it can be used inside templates.
func (*Request) Register ¶
Register calls RegisterEventFn(id, nil). Useful in template constructs like:
<div jid="{{$.Register `foo`}}">
func (*Request) RegisterEventFn ¶
RegisterEventFn records the given HTML 'jid' attribute as a valid target for dynamic updates using the given event function (which may be nil).
If the jid argument is an empty string, a unique jid will be generated.
If fn argument is nil, a pre-existing event function won't be overwritten.
Returns the (possibly generated) jid.
func (*Request) RemoveAttr ¶
RemoveAttr removes a given attribute from the HTML element(s) for the current Request only.
Only the requests that have registered the 'jid' (either with Register or OnEvent) will be sent the message.
func (*Request) Select ¶
func (rq *Request) Select(jid string, val *NamedBoolArray, fn InputTextFn, attrs ...string) template.HTML
func (*Request) Send ¶
Send a message to the current Request only. Returns true if the message was successfully sent.
func (*Request) ServeHTTP ¶
func (rq *Request) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements http.HanderFunc
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) SetAttr ¶
SetAttr sets an attribute on the HTML element(s) on the current Request only. If the value is an empty string, a value-less attribute will be added (such as "disabled").
Only the requests that have registered the 'jid' (either with Register or OnEvent) will be sent the message.
func (*Request) SetBoolValue ¶
SetBoolValue sends a jid and new input value to all Requests except this one.
Only the requests that have registered the jid (either with Register or OnEvent) will be sent the message.
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) SetDateValue ¶
SetDateValue sends a jid and new input value to all Requests except this one.
Only the requests that have registered the jid (either with Register or OnEvent) will be sent the message.
func (*Request) SetEventFn ¶
SetEventFn sets the event function for the given jid to be the given function. Passing nil for the function is legal, and has the effect of ensuring the jid can be the target of DOM updates but not to send Javascript events. Note that you can only have one event function per jid.
func (*Request) SetFloatValue ¶
SetFloatValue sends a jid and new input value to all Requests except this one.
Only the requests that have registered the jid (either with Register or OnEvent) will be sent the message.
func (*Request) SetInner ¶
SetInner sends a jid and new inner HTML to all Requests except this one.
Only the requests that have registered the 'jid' (either with Register or OnEvent) will be sent the message.
func (*Request) SetTextValue ¶
SetTextValue sends a jid and new input value to all Requests except this one.
Only the requests that have registered the jid (either with Register or OnEvent) will be sent the message.
type Session ¶ added in v0.11.0
type Session struct {
// contains filtered or unexported fields
}
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.
Returns the a cookie to be sent to the client browser that will delete the browser cookie. Returns nil if the session was not found or is already closed. It is safe to call on a nil Session.
func (*Session) Cookie ¶ added in v0.11.0
Cookie returns the 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 cookie value for the Session. 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) GetExpires ¶ added in v0.11.0
GetExpires gets the Session expiry time. It is safe to call on a nil or closed Session, in which case it returns a zero time.
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) Refresh ¶ added in v0.14.0
Refresh ensures the cookie expiry is at least `minAge` seconds in the future. Returns a session cookie to be set if it's expiry time was updated, or nil. It is safe to call on a nil Session, in which case it returns nil.
func (*Session) Reload ¶ added in v0.17.0
func (sess *Session) Reload()
Reload sends a message to all Requests using this session to reload their webpage. It is safe to call on a nil Session.
func (*Session) Set ¶ added in v0.11.0
Set sets a value to be associated with the key. If value is nil, the key is removed from the session. It is safe to call on a nil Session.
func (*Session) SetExpires ¶ added in v0.11.0
SetExpires sets the Session expiry time. Attempts to set a zero time will be ignored; use Close() to close the session. It is safe to call on a nil Session.