This repository has been archived by the owner on Aug 28, 2022. It is now read-only.
/
main.go
137 lines (117 loc) · 2.6 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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package main
import (
"github.com/brendonmatos/golive"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/websocket/v2"
)
type Writer string
type Genre string
type Book struct {
Writer
Genre
Name string
}
type BooksFilter struct {
Do bool
Writer
Genre
}
type Books struct {
golive.LiveComponentWrapper
Filter BooksFilter
List []Book
}
func NewBooks() *Books {
return &Books{
List: []Book{
{
Writer: "J. K. Rowling",
Genre: "fantasy",
Name: "Harry Potter and the Philosopher's Stone",
},
{
Writer: "Caleb Doxsey",
Genre: "programming",
Name: "Introducing Go: Build Reliable, Scalable Programs",
},
{
Writer: "Marijn Haverbeke",
Genre: "programming",
Name: "Eloquent JavaScript: A Modern Introduction to Programming",
},
},
Filter: BooksFilter{
Do: true,
Genre: "",
Writer: "",
},
}
}
func NewBooksComponent() *golive.LiveComponent {
return golive.NewLiveComponent("Books", NewBooks())
}
func (b *Books) GetFilteredList() []Book {
filtered := make([]Book, 0)
for _, book := range b.List {
match := true
if b.Filter.Genre != "" && book.Genre != b.Filter.Genre {
match = false
}
if b.Filter.Writer != "" && book.Writer != b.Filter.Writer {
match = false
}
if match {
filtered = append(filtered, book)
}
}
return filtered
}
func (b *Books) SetFilterWriter(data map[string]string) {
b.Filter.Do = !b.Filter.Do
if name, ok := data["writer"]; ok {
b.Filter.Writer = Writer(name)
}
}
func (b *Books) GetWriters() []Writer {
writers := make([]Writer, 0)
book:
for _, book := range b.List {
for _, writer := range writers {
if writer == book.Writer {
continue book
}
}
writers = append(writers, book.Writer)
}
return writers
}
func (b *Books) TemplateHandler(_ *golive.LiveComponent) string {
return `
<div>
<select go-live-input="Filter.Writer">
<option value="">No Filter</option>
{{ range $index, $writer := .GetWriters }}
<option value="{{$writer}}">{{$writer}}</option>
{{ end }}
</select>
<div>
{{ range $index, $Book := .GetFilteredList }}
<div style="border: 1px solid black; padding: 10px;" key="{{$index}}">
<span><b>name:</b> {{ $Book.name }}</span><br>
<span><b>Writer:</b> {{ $Book.Writer }}</span>
</div>
{{ end }}
</div>
</div>
`
}
func main() {
app := fiber.New()
liveServer := golive.NewServer()
app.Get("/", liveServer.CreateHTMLHandler(NewBooksComponent, golive.PageContent{
Lang: "us",
Title: "Hello world",
}))
app.Get("/ws", websocket.New(liveServer.HandleWSRequest))
_ = app.Listen(":3000")
}