Documentation ¶
Overview ¶
Example ¶
Example shows a simple temperature control using the "live-click" event.
package main import ( "bytes" "context" "html/template" "io" "net/http" ) // Model of our thermostat. type ThermoModel struct { C float32 } // Helper function to get the model from the socket data. func NewThermoModel(s Socket) *ThermoModel { m, ok := s.Assigns().(*ThermoModel) // If we haven't already initialised set up. if !ok { m = &ThermoModel{ C: 19.5, } } return m } // thermoMount initialises the thermostat state. Data returned in the mount function will // automatically be assigned to the socket. func thermoMount(ctx context.Context, s Socket) (interface{}, error) { return NewThermoModel(s), nil } // tempUp on the temp up event, increase the thermostat temperature by .1 C. An EventHandler function // is called with the original request context of the socket, the socket itself containing the current // state and and params that came from the event. Params contain query string parameters and any // `live-value-` bindings. func tempUp(ctx context.Context, s Socket, p Params) (interface{}, error) { model := NewThermoModel(s) model.C += 0.1 return model, nil } // tempDown on the temp down event, decrease the thermostat temperature by .1 C. func tempDown(ctx context.Context, s Socket, p Params) (interface{}, error) { model := NewThermoModel(s) model.C -= 0.1 return model, nil } // Example shows a simple temperature control using the // "live-click" event. func main() { // Setup the handler. h := NewHandler() // Mount function is called on initial HTTP load and then initial web // socket connection. This should be used to create the initial state, // the socket Connected func will be true if the mount call is on a web // socket connection. h.HandleMount(thermoMount) // Provide a render function. Here we are doing it manually, but there is a // provided WithTemplateRenderer which can be used to work with `html/template` h.HandleRender(func(ctx context.Context, data interface{}) (io.Reader, error) { tmpl, err := template.New("thermo").Parse(` <div>{{.C}}</div> <button live-click="temp-up">+</button> <button live-click="temp-down">-</button> <!-- Include to make live work --> <script src="/live.js"></script> `) if err != nil { return nil, err } var buf bytes.Buffer if err := tmpl.Execute(&buf, data); err != nil { return nil, err } return &buf, nil }) // This handles the `live-click="temp-up"` button. First we load the model from // the socket, increment the temperature, and then return the new state of the // model. Live will now calculate the diff between the last time it rendered and now, // produce a set of diffs and push them to the browser to update. h.HandleEvent("temp-up", tempUp) // This handles the `live-click="temp-down"` button. h.HandleEvent("temp-down", tempDown) http.Handle("/thermostat", NewHttpHandler(NewCookieStore("session-name", []byte("weak-secret")), h)) // This serves the JS needed to make live work. http.Handle("/live.js", Javascript{}) http.ListenAndServe(":8080", nil) }
Output:
Index ¶
- Constants
- Variables
- func NewID() string
- func RenderSocket(ctx context.Context, e Engine, s Socket) (*html.Node, error)
- func Request(ctx context.Context) *http.Request
- func SessionID(session Session) string
- func Writer(ctx context.Context) http.ResponseWriter
- type BaseEngine
- func (e *BaseEngine) AddSocket(sock Socket)
- func (e *BaseEngine) Broadcast(event string, data interface{}) error
- func (e *BaseEngine) CallEvent(ctx context.Context, t string, sock Socket, msg Event) error
- func (e *BaseEngine) CallParams(ctx context.Context, sock Socket, msg Event) error
- func (e *BaseEngine) DeleteSocket(sock Socket)
- func (e *BaseEngine) Error() ErrorHandler
- func (e *BaseEngine) HandleBroadcast(f BroadcastHandler)
- func (e *BaseEngine) Handler(hand Handler)
- func (e *BaseEngine) Mount() MountHandler
- func (e *BaseEngine) Params() []EventHandler
- func (e *BaseEngine) Render() RenderHandler
- type BaseHandler
- func (h *BaseHandler) HandleError(f ErrorHandler)
- func (h *BaseHandler) HandleEvent(t string, handler EventHandler)
- func (h *BaseHandler) HandleMount(f MountHandler)
- func (h *BaseHandler) HandleParams(handler EventHandler)
- func (h *BaseHandler) HandleRender(f RenderHandler)
- func (h *BaseHandler) HandleSelf(t string, handler SelfHandler)
- type BaseSocket
- func (s *BaseSocket) Assign(data interface{})
- func (s *BaseSocket) Assigns() interface{}
- func (s *BaseSocket) Broadcast(event string, data interface{}) error
- func (s *BaseSocket) Connected() bool
- func (s *BaseSocket) ID() SocketID
- func (s *BaseSocket) LatestRender() *html.Node
- func (s *BaseSocket) Messages() chan Event
- func (s *BaseSocket) PatchURL(values url.Values)
- func (s *BaseSocket) Redirect(u *url.URL)
- func (s *BaseSocket) Self(ctx context.Context, event string, data interface{}) error
- func (s *BaseSocket) Send(event string, data interface{}, options ...EventConfig) error
- func (s *BaseSocket) Session() Session
- func (s *BaseSocket) UpdateRender(render *html.Node)
- type BroadcastHandler
- type CookieStore
- type Engine
- type ErrorEvent
- type ErrorHandler
- type Event
- type EventConfig
- type EventHandler
- type Handler
- type HandlerConfig
- type HttpEngine
- type HttpSessionStore
- type HttpSocket
- type Javascript
- type JavascriptMap
- type LocalTransport
- type MountHandler
- type Params
- type Patch
- type PatchAction
- type PubSub
- type PubSubTransport
- type RenderHandler
- type SelfHandler
- type Session
- type Socket
- type SocketID
- type TransportMessage
Examples ¶
Constants ¶
const ( // EventError indicates an error has occured. EventError = "err" // EventPatch a patch event containing a diff. EventPatch = "patch" // EventAck sent when an event is ackknowledged. EventAck = "ack" // EventConnect sent as soon as the server accepts the // WS connection. EventConnect = "connect" // EventParams sent for a URL parameter update. Can be // sent both directions. EventParams = "params" // EventRedirect sent in order to trigger a browser // redirect. EventRedirect = "redirect" )
const LiveRendered = "live-rendered"
LiveRendered an attribute key to show that a DOM has been rendered by live.
Variables ¶
var ErrMessageMalformed = errors.New("message malformed")
ErrMessageMalformed returned when a message could not be parsed correctly.
var ErrNoEventHandler = errors.New("view missing event handler")
ErrNoEventHandler returned when a handler has no event handler for that event.
var ErrNoRenderer = errors.New("no renderer has been set on the handler")
ErrNoRenderer returned when no renderer has been set on the handler.
var ErrNoSocket = errors.New("no socket")
ErrNoSocket returned when a socket doesn't exist.
var ErrNotImplemented = errors.New("not implemented")
ErrNotImplemented returned when an interface has not been implemented correctly.
Functions ¶
func RenderSocket ¶ added in v0.13.0
RenderSocket takes the engine and current socket and renders it to html.
Types ¶
type BaseEngine ¶ added in v0.13.0
type BaseEngine struct {
// contains filtered or unexported fields
}
BaseEngine handles live inner workings.
func NewBaseEngine ¶ added in v0.13.0
func NewBaseEngine(h Handler) *BaseEngine
NewBaseEngine creates a new base engine.
func (*BaseEngine) AddSocket ¶ added in v0.13.0
func (e *BaseEngine) AddSocket(sock Socket)
AddSocket add a socket to the engine.
func (*BaseEngine) Broadcast ¶ added in v0.13.0
func (e *BaseEngine) Broadcast(event string, data interface{}) error
Broadcast send a message to all sockets connected to this engine.
func (*BaseEngine) CallParams ¶ added in v0.13.0
CallParams on params change run the handler.
func (*BaseEngine) DeleteSocket ¶ added in v0.13.0
func (e *BaseEngine) DeleteSocket(sock Socket)
DeleteSocket remove a socket from the engine.
func (*BaseEngine) Error ¶ added in v0.13.0
func (e *BaseEngine) Error() ErrorHandler
func (*BaseEngine) HandleBroadcast ¶ added in v0.13.0
func (e *BaseEngine) HandleBroadcast(f BroadcastHandler)
func (*BaseEngine) Handler ¶ added in v0.13.0
func (e *BaseEngine) Handler(hand Handler)
func (*BaseEngine) Mount ¶ added in v0.13.0
func (e *BaseEngine) Mount() MountHandler
func (*BaseEngine) Params ¶ added in v0.13.0
func (e *BaseEngine) Params() []EventHandler
func (*BaseEngine) Render ¶ added in v0.13.0
func (e *BaseEngine) Render() RenderHandler
type BaseHandler ¶ added in v0.13.0
type BaseHandler struct {
// contains filtered or unexported fields
}
BaseHandler.
func NewHandler ¶
func NewHandler(configs ...HandlerConfig) *BaseHandler
NewHandler sets up a base handler for live.
func (*BaseHandler) HandleError ¶ added in v0.13.0
func (h *BaseHandler) HandleError(f ErrorHandler)
func (*BaseHandler) HandleEvent ¶ added in v0.13.0
func (h *BaseHandler) HandleEvent(t string, handler EventHandler)
HandleEvent handles an event that comes from the client. For example a click from `live-click="myevent"`.
func (*BaseHandler) HandleMount ¶ added in v0.13.0
func (h *BaseHandler) HandleMount(f MountHandler)
func (*BaseHandler) HandleParams ¶ added in v0.13.0
func (h *BaseHandler) HandleParams(handler EventHandler)
HandleParams handles a URL query parameter change. This is useful for handling things like pagincation, or some filtering.
func (*BaseHandler) HandleRender ¶ added in v0.13.0
func (h *BaseHandler) HandleRender(f RenderHandler)
func (*BaseHandler) HandleSelf ¶ added in v0.13.0
func (h *BaseHandler) HandleSelf(t string, handler SelfHandler)
HandleSelf handles an event that comes from the server side socket. For example calling h.Self(socket, msg) will be handled here.
type BaseSocket ¶ added in v0.13.0
type BaseSocket struct {
// contains filtered or unexported fields
}
BaseSocket describes a socket from the outside.
func NewBaseSocket ¶ added in v0.13.0
func NewBaseSocket(s Session, e Engine, connected bool) *BaseSocket
NewBaseSocket creates a new default socket.
func (*BaseSocket) Assign ¶ added in v0.13.0
func (s *BaseSocket) Assign(data interface{})
Assign set data to this socket. This will happen automatically if you return data from and `EventHander`.
func (*BaseSocket) Assigns ¶ added in v0.13.0
func (s *BaseSocket) Assigns() interface{}
Assigns returns the data currently assigned to this socket.
func (*BaseSocket) Broadcast ¶ added in v0.13.0
func (s *BaseSocket) Broadcast(event string, data interface{}) error
Broadcast send an event to all sockets on this same engine.
func (*BaseSocket) Connected ¶ added in v0.13.0
func (s *BaseSocket) Connected() bool
Connected returns if this socket is connected via the websocket.
func (*BaseSocket) ID ¶ added in v0.13.0
func (s *BaseSocket) ID() SocketID
ID generate a unique ID for this socket.
func (*BaseSocket) LatestRender ¶ added in v0.13.0
func (s *BaseSocket) LatestRender() *html.Node
func (*BaseSocket) Messages ¶ added in v0.13.0
func (s *BaseSocket) Messages() chan Event
func (*BaseSocket) PatchURL ¶ added in v0.13.0
func (s *BaseSocket) PatchURL(values url.Values)
PatchURL sends an event to the client to update the query params in the URL.
func (*BaseSocket) Redirect ¶ added in v0.13.0
func (s *BaseSocket) Redirect(u *url.URL)
Redirect sends a redirect event to the client. This will trigger the browser to redirect to a URL.
func (*BaseSocket) Self ¶ added in v0.13.0
func (s *BaseSocket) Self(ctx context.Context, event string, data interface{}) error
Self send an event to this socket itself. Will be handled in the handlers HandleSelf function.
func (*BaseSocket) Send ¶ added in v0.13.0
func (s *BaseSocket) Send(event string, data interface{}, options ...EventConfig) error
Send an event to this socket's client, to be handled there.
func (*BaseSocket) Session ¶ added in v0.13.0
func (s *BaseSocket) Session() Session
func (*BaseSocket) UpdateRender ¶ added in v0.13.0
func (s *BaseSocket) UpdateRender(render *html.Node)
type BroadcastHandler ¶ added in v0.13.0
BroadcastHandler a way for processes to communicate.
type CookieStore ¶ added in v0.2.0
type CookieStore struct { Store *sessions.CookieStore // contains filtered or unexported fields }
CookieStore a `gorilla/sessions` based cookie store.
func NewCookieStore ¶ added in v0.2.0
func NewCookieStore(sessionName string, keyPairs ...[]byte) *CookieStore
NewCookieStore create a new `gorilla/sessions` based cookie store.
func (CookieStore) Clear ¶ added in v0.12.3
func (c CookieStore) Clear(w http.ResponseWriter, r *http.Request) error
Clear a session.
func (CookieStore) Get ¶ added in v0.2.0
func (c CookieStore) Get(r *http.Request) (Session, error)
Get get a session.
func (CookieStore) Save ¶ added in v0.2.0
func (c CookieStore) Save(w http.ResponseWriter, r *http.Request, session Session) error
Save a session.
type Engine ¶ added in v0.13.0
type Engine interface { // Handler takes a handler to configure the lifecycle. Handler(h Handler) // Mount a user should provide the mount function. This is what // is called on initial GET request and later when the websocket connects. // Data to render the handler should be fetched here and returned. Mount() MountHandler // Params called to handle any incoming paramters after mount. Params() []EventHandler // Render is called to generate the HTML of a Socket. It is defined // by default and will render any template provided. Render() RenderHandler // Error is called when an error occurs during the mount and render // stages of the handler lifecycle. Error() ErrorHandler // AddSocket add a socket to the engine. AddSocket(sock Socket) // DeleteSocket remove a socket from the engine. DeleteSocket(sock Socket) // CallParams on params change run the handlers. CallParams(ctx context.Context, sock Socket, msg Event) error // CallEvent route an event to the correct handler. CallEvent(ctx context.Context, t string, sock Socket, msg Event) error // HandleBroadcast allows overriding the broadcast functionality. HandleBroadcast(handler BroadcastHandler) // Broadcast send a message to all sockets connected to this engine. Broadcast(event string, data interface{}) error // contains filtered or unexported methods }
Engine methods.
type ErrorEvent ¶ added in v0.13.0
type ErrorHandler ¶ added in v0.3.0
ErrorHandler if an error occurs during the mount and render cycle a handler of this type will be called.
type Event ¶
type Event struct { T string `json:"t"` ID int `json:"i,omitempty"` Data json.RawMessage `json:"d,omitempty"` SelfData interface{} `json:"-"` }
Event messages that are sent and received by the socket.
type EventConfig ¶ added in v0.10.0
EventConfig configures an event.
type EventHandler ¶
EventHandler a function to handle events, returns the data that should be set to the socket after handling.
type Handler ¶
type Handler interface { // HandleMount handles initial setup on first request, and then later when // the socket first connets. HandleMount(handler MountHandler) // HandleRender used to set the render method for the handler. HandleRender(handler RenderHandler) // HandleError for when an error occurs. HandleError(handler ErrorHandler) // HandleEvent handles an event that comes from the client. For example a click // from `live-click="myevent"`. HandleEvent(t string, handler EventHandler) // HandleSelf handles an event that comes from the server side socket. For example calling // h.Self(socket, msg) will be handled here. HandleSelf(t string, handler SelfHandler) // HandleParams handles a URL query parameter change. This is useful for handling // things like pagincation, or some filtering. HandleParams(handler EventHandler) // contains filtered or unexported methods }
Handler methods.
type HandlerConfig ¶
HandlerConfig applies config to a handler.
func WithTemplateRenderer ¶ added in v0.6.0
func WithTemplateRenderer(t *template.Template) HandlerConfig
WithTemplateRenderer set the handler to use an `html/template` renderer.
type HttpEngine ¶ added in v0.13.0
type HttpEngine struct { *BaseEngine // contains filtered or unexported fields }
HttpEngine serves live for net/http.
func NewHttpHandler ¶ added in v0.13.0
func NewHttpHandler(store HttpSessionStore, handler Handler) *HttpEngine
NewHttpHandler returns the net/http handler for live.
func (*HttpEngine) ServeHTTP ¶ added in v0.13.0
func (h *HttpEngine) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP serves this handler.
type HttpSessionStore ¶ added in v0.13.0
type HttpSessionStore interface { Get(*http.Request) (Session, error) Save(http.ResponseWriter, *http.Request, Session) error Clear(http.ResponseWriter, *http.Request) error }
HttpSessionStore handles storing and retrieving sessions.
type HttpSocket ¶ added in v0.13.0
type HttpSocket struct {
*BaseSocket
}
func NewHttpSocket ¶ added in v0.13.0
func NewHttpSocket(s Session, e Engine, connected bool) *HttpSocket
NewHttpSocket creates a new http socket.
type Javascript ¶
type Javascript struct { }
Javascript handles serving the client side portion of live.
func (Javascript) ServeHTTP ¶
func (j Javascript) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP.
type JavascriptMap ¶
type JavascriptMap struct { }
JavascriptMap handles serving source map.
func (JavascriptMap) ServeHTTP ¶
func (j JavascriptMap) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP.
type LocalTransport ¶ added in v0.10.0
type LocalTransport struct {
// contains filtered or unexported fields
}
LocalTransport a pubsub transport that allows handlers to communicate locally.
func NewLocalTransport ¶ added in v0.10.0
func NewLocalTransport() *LocalTransport
NewLocalTransport create a new LocalTransport.
type MountHandler ¶
MountHandler the func that is called by a handler to gather data to be rendered in a template. This is called on first GET and then later when the web socket first connects. It should return the state to be maintained in the socket.
type Params ¶ added in v0.10.0
type Params map[string]interface{}
Params event params.
func NewParamsFromRequest ¶ added in v0.10.0
NewParamsFromRequest helper to generate Params from an http request.
func (Params) Checkbox ¶ added in v0.10.0
Checkbox helper to return a boolean from params referring to a checkbox input.
type Patch ¶
type Patch struct { Anchor string Action PatchAction HTML string }
Patch a location in the frontend dom.
type PatchAction ¶
type PatchAction uint32
PatchAction available actions to take by a patch.
const ( Noop PatchAction = iota Replace Append Prepend )
Actions available.
type PubSub ¶ added in v0.10.0
type PubSub struct {
// contains filtered or unexported fields
}
PubSub handles communication between handlers. Depending on the given transport this could be between handlers in an application, or across nodes in a cluster.
func NewPubSub ¶ added in v0.10.0
func NewPubSub(ctx context.Context, t PubSubTransport) *PubSub
NewPubSub creates a new PubSub handler.
type PubSubTransport ¶ added in v0.10.0
type PubSubTransport interface { // Publish a message onto the given topic. Publish(ctx context.Context, topic string, msg Event) error // Listen will be called in a go routine so should be written to // block. Listen(ctx context.Context, p *PubSub) error }
PubSubTransport is how the messages should be sent to the listeners.
type RenderHandler ¶
RenderHandler the func that is called to render the current state of the data for the socket.
type SelfHandler ¶ added in v0.14.0
SelfHandler a function to handle self events, returns the data that should be set to the socket after handling.
type Socket ¶
type Socket interface { // ID return an ID for this socket. ID() SocketID // Assigns returns the data currently assigned to this // socket. Assigns() interface{} // Assign set data to this socket. This will happen automatically // if you return data from and `EventHander`. Assign(data interface{}) // Connected returns true if this socket is connected via the websocket. Connected() bool // Self send an event to this socket itself. Will be handled in the // handlers HandleSelf function. Self(ctx context.Context, event string, data interface{}) error // Broadcast send an event to all sockets on this same engine. Broadcast(event string, data interface{}) error // Send an event to this socket's client, to be handled there. Send(event string, data interface{}, options ...EventConfig) error // PatchURL sends an event to the client to update the // query params in the URL. PatchURL(values url.Values) // Redirect sends a redirect event to the client. This will trigger the browser to // redirect to a URL. Redirect(u *url.URL) // LatestRender return the latest render that this socket generated. LatestRender() *html.Node // UpdateRender set the latest render. UpdateRender(render *html.Node) // Session returns the sockets session. Session() Session // Messages returns the channel of events on this socket. Messages() chan Event }
Socket describes a connected user, and the state that they are in.
type TransportMessage ¶ added in v0.10.0
TransportMessage a userful container to send live events.