Documentation ¶
Overview ¶
Example (Temperature) ¶
Example_temperature shows a simple temperature control using the "live-click" event.
// Model of our thermostat. type ThermoModel struct { C float32 } // Helper function to get the model from the socket data. NewThermoModel := func(s *Socket) *ThermoModel { m, ok := s.Assigns().(*ThermoModel) if !ok { m = &ThermoModel{ C: 19.5, } } return m } // Parsing nil as a template to NewHandler will error if we do not set // a render function ourselves. h, err := NewHandler(nil, NewCookieStore("session-name", []byte("weak-secret"))) if err != nil { log.Fatal("could not create handler") } // By default the handler will automatically render any template parsed into the // NewHandler function. However you can override and render an HTML string like // this. h.Render = func(ctc context.Context, t *template.Template, 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 } // Mount function is called on initial HTTP load and then initial web // socket connection. This should be used to create the initial state, // the connected variable will be true if the mount call is on a web // socket connection. h.Mount = func(ctx context.Context, h *Handler, r *http.Request, s *Socket, connected bool) (interface{}, error) { return NewThermoModel(s), 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", func(s *Socket, _ map[string]interface{}) (interface{}, error) { model := NewThermoModel(s) model.C += 0.1 return model, nil }) // This handles the `live-click="temp-down"` button. h.HandleEvent("temp-down", func(s *Socket, _ map[string]interface{}) (interface{}, error) { model := NewThermoModel(s) model.C -= 0.1 return model, nil }) 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 ParamFloat32(params map[string]interface{}, key string) float32
- func ParamInt(params map[string]interface{}, key string) int
- func ParamString(params map[string]interface{}, key string) string
- func StartHandler(h *Handler)
- type CookieStore
- type Event
- type EventHandler
- type Handler
- type HandlerConfig
- type HandlerEvent
- type Javascript
- type JavascriptMap
- type MountHandler
- type Patch
- type PatchAction
- type RenderHandler
- type Session
- type SessionStore
- type Socket
- type ValueKey
Examples ¶
Constants ¶
const ( // EventError indicates an error has occured. EventError = "err" // EventPatch a patch event containing a diff. EventPatch = "patch" )
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 ErrNoSocket = errors.New("no socket")
ErrNoSocket returned when a socket doesn't exist.
Functions ¶
func ParamFloat32 ¶
ParamFloat32 helper to return a float32 from the params.
func ParamString ¶
ParamString helper to return a string from the params.
func StartHandler ¶
func StartHandler(h *Handler)
StartHandler run a handler so that it's events can be dealt with. This is called by `NewHandler` so is only required if you are manually creating a handler.
Types ¶
type CookieStore ¶ added in v0.2.0
type CookieStore struct {
// 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) 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 Event ¶
type Event struct { T string `json:"t"` Data interface{} `json:"d"` }
Event messages that are sent and received by the socket.
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 MountHandler Render RenderHandler // contains filtered or unexported fields }
Handler to be served by an HTTP server.
func NewHandler ¶
func NewHandler(t *template.Template, 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) HandleSelf ¶
func (h *Handler) HandleSelf(t string, handler EventHandler)
HandleSelf handles an event that comes from the view. For example calling view.Self(socket, msg) will be handled here.
type HandlerConfig ¶
HandlerConfig applies config to a handler.
func WithRootTemplate ¶
func WithRootTemplate(rootTemplate string) HandlerConfig
WithRootTemplate set the renderer to use a different root template. This changes the handlers Render function.
type HandlerEvent ¶
HandlerEvent an event sent by the handler.
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 MountHandler ¶
type MountHandler func(ctx context.Context, h *Handler, r *http.Request, c *Socket, connected bool) (interface{}, error)
MountHandler when mount is reached.
type Patch ¶
type Patch struct { Path []int 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 Insert Replace Append Prepend )
Actions available.
type RenderHandler ¶
type RenderHandler func(ctx context.Context, t *template.Template, data interface{}) (io.Reader, error)
RenderHandler when the view is asked to render.
type Session ¶
type Session struct {
ID string
}
Session what we will actually store across page loads.
type SessionStore ¶ added in v0.2.0
type SessionStore interface { Get(*http.Request) (Session, error) Save(http.ResponseWriter, *http.Request, Session) error }
SessionStore handles storing and retrieving sessions.
type Socket ¶
type Socket struct { 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`.