Documentation ¶
Overview ¶
Example ¶
Example shows a simple temperature control using the "live-click" event.
package main import ( "bytes" "context" "html/template" "io" "log" "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, r *http.Request, 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, err := NewHandler(NewCookieStore("session-name", []byte("weak-secret"))) if err != nil { log.Fatal("could not create handler") } // 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.Mount = 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.Render = 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", 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 SessionID(session Session) string
- type CookieStore
- type ErrorHandler
- type Event
- type EventConfig
- type EventHandler
- type Handler
- func (h *Handler) Broadcast(event string, data interface{}) error
- func (h *Handler) HandleEvent(t string, handler EventHandler)
- func (h *Handler) HandleParams(handler EventHandler)
- func (h *Handler) HandleSelf(t string, handler EventHandler)
- func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)
- type HandlerConfig
- type Javascript
- type JavascriptMap
- type LocalTransport
- type MountHandler
- type Params
- type Patch
- type PatchAction
- type PubSub
- type PubSubTransport
- type RenderHandler
- type Session
- type SessionStore
- type Socket
- func (s *Socket) Assign(data interface{})
- func (s *Socket) Assigns() interface{}
- func (s *Socket) Broadcast(event string, data interface{}) error
- func (s *Socket) Connected() bool
- func (s *Socket) PatchURL(values url.Values)
- func (s *Socket) Redirect(u *url.URL)
- func (s *Socket) Self(ctx context.Context, event string, data interface{}) error
- func (s *Socket) Send(event string, data interface{}, options ...EventConfig) error
- 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.
Functions ¶
Types ¶
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 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"` }
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 struct { // 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 // 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 // contains filtered or unexported fields }
Handler to be served by an HTTP server.
func NewHandler ¶
func NewHandler(store SessionStore, configs ...HandlerConfig) (*Handler, error)
NewHandler creates a new live handler.
func (*Handler) HandleEvent ¶
func (h *Handler) HandleEvent(t string, handler EventHandler)
HandleEvent handles an event that comes from the client. For example a click from `live-click="myevent"`.
func (*Handler) HandleParams ¶ added in v0.8.0
func (h *Handler) HandleParams(handler EventHandler)
HandleParams handles a URL query parameter change. This is useful for handling things like pagincation, or some filtering.
func (*Handler) HandleSelf ¶
func (h *Handler) HandleSelf(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.
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 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.
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 SessionStore ¶ added in v0.2.0
type SessionStore interface { Get(*http.Request) (Session, error) Save(http.ResponseWriter, *http.Request, Session) error Clear(http.ResponseWriter, *http.Request) error }
SessionStore handles storing and retrieving sessions.
type Socket ¶
type Socket struct { // The session for this socket. Session Session // contains filtered or unexported fields }
Socket describes a socket from the outside.
func (*Socket) Assign ¶
func (s *Socket) Assign(data interface{})
Assign set data to this socket. This will happen automatically if you return data from and `EventHander`.
func (*Socket) Assigns ¶
func (s *Socket) Assigns() interface{}
Assigns returns the data currently assigned to this socket.
func (*Socket) Broadcast ¶ added in v0.9.0
Broadcast send an event to all sockets on this same handler.
func (*Socket) Connected ¶ added in v0.9.0
Connected returns if this socket is connected via the websocket.
func (*Socket) PatchURL ¶ added in v0.8.0
PatchURL sends an event to the client to update the query params in the URL.
func (*Socket) Redirect ¶ added in v0.8.0
Redirect sends a redirect event to the client. This will trigger the browser to redirect to a URL.
type TransportMessage ¶ added in v0.10.0
TransportMessage a userful container to send live events.