-
Notifications
You must be signed in to change notification settings - Fork 27
/
main.go
98 lines (86 loc) · 2.04 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
package main
import (
"context"
"fmt"
"html/template"
"log"
"net/http"
"github.com/jfyne/live"
)
const (
validate = "validate"
save = "save"
)
type form struct {
Errors map[string]string
}
type model struct {
Messages []string
Form form
}
func newModel(s *live.Socket) *model {
m, ok := s.Assigns().(*model)
if !ok {
return &model{
Form: form{
Errors: map[string]string{},
},
}
}
// Clear errors on each event as we recheck each
// time.
m.Form.Errors = map[string]string{}
return m
}
func main() {
t, err := template.ParseFiles("examples/root.html", "examples/form/view.html")
if err != nil {
log.Fatal(err)
}
h, err := live.NewHandler(t, live.NewCookieStore("session-name", []byte("weak-secret")))
if err != nil {
log.Fatal(err)
}
// Set the mount function for this handler.
h.Mount = func(ctx context.Context, h *live.Handler, r *http.Request, s *live.Socket, connected bool) (interface{}, error) {
// This will initialise the form.
return newModel(s), nil
}
// Client side events.
validateMessage := func(msg string) string {
if len(msg) < 10 {
return fmt.Sprintf("Length of 10 required, have %d", len(msg))
}
if len(msg) > 20 {
return fmt.Sprintf("Your message is too long > 20, have %d", len(msg))
}
return ""
}
// Validate the form.
h.HandleEvent(validate, func(s *live.Socket, p map[string]interface{}) (interface{}, error) {
m := newModel(s)
msg := live.ParamString(p, "message")
vm := validateMessage(msg)
if vm != "" {
m.Form.Errors["message"] = vm
}
return m, nil
})
// Handle form saving.
h.HandleEvent(save, func(s *live.Socket, p map[string]interface{}) (interface{}, error) {
m := newModel(s)
msg := live.ParamString(p, "message")
vm := validateMessage(msg)
if vm != "" {
m.Form.Errors["message"] = vm
} else {
m.Messages = append(m.Messages, msg)
}
return m, nil
})
// Run the server.
http.Handle("/form", h)
http.Handle("/live.js", live.Javascript{})
http.Handle("/auto.js.map", live.JavascriptMap{})
http.ListenAndServe(":8080", nil)
}