-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
423 lines (371 loc) · 8.85 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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
package main
import (
"embed"
"fmt"
"html/template"
"log"
"net/http"
"slices"
"strconv"
"sync"
"time"
"github.com/olahol/melody"
"gorm.io/driver/sqlite"
"gorm.io/gorm"
)
type App struct {
todoService TodoCrud
m *melody.Melody
indexTmpl *template.Template
renameTmpl *template.Template
assets embed.FS
db *gorm.DB
}
type ToDo struct {
gorm.Model
ID int
Title string
Done bool
}
type TodoCrud interface {
All() []ToDo
Find(id int) (ToDo, error)
Add(todo ToDo)
Toggle(id int)
Delete(id int)
Rename(id int, title string)
Clear()
ClearCompleted()
OpenTodos() []ToDo
CompletedTodos() []ToDo
}
type TodoServiceMemory struct {
TodoCrud
sync.Mutex
TodoList []ToDo
ToDoID int
}
func (t *TodoServiceMemory) OpenTodos() []ToDo {
t.Lock()
defer t.Unlock()
openTodos := []ToDo{}
for _, todo := range t.TodoList {
if !todo.Done {
openTodos = append(openTodos, todo)
}
}
return openTodos
}
func (t *TodoServiceMemory) CompletedTodos() []ToDo {
t.Lock()
defer t.Unlock()
completedTodos := []ToDo{}
for _, todo := range t.TodoList {
if todo.Done {
completedTodos = append(completedTodos, todo)
}
}
return completedTodos
}
func (t *TodoServiceMemory) All() []ToDo {
t.Lock()
defer t.Unlock()
// make a copy of the list
todoList := make([]ToDo, len(t.TodoList))
copy(todoList, t.TodoList)
// reverse the copy
slices.Reverse(todoList)
return todoList
}
func (t *TodoServiceMemory) Find(id int) (todo ToDo, err error) {
t.Lock()
defer t.Unlock()
for _, todo := range t.TodoList {
if todo.ID == id {
return todo, nil
}
}
return todo, fmt.Errorf("todo with id %d not found", id)
}
func (t *TodoServiceMemory) Add(todo ToDo) {
t.Lock()
defer t.Unlock()
todo.ID = t.ToDoID
t.TodoList = append(t.TodoList, todo)
t.ToDoID++
}
func (t *TodoServiceMemory) Toggle(id int) {
t.Lock()
defer t.Unlock()
for i, todo := range t.TodoList {
if todo.ID == id {
t.TodoList[i].Done = !todo.Done
break
}
}
}
func (t *TodoServiceMemory) Delete(id int) {
t.Lock()
defer t.Unlock()
for i, todo := range t.TodoList {
if todo.ID == id {
t.TodoList = append(t.TodoList[:i], t.TodoList[i+1:]...)
break
}
}
}
func (t *TodoServiceMemory) Rename(id int, title string) {
t.Lock()
defer t.Unlock()
for i, todo := range t.TodoList {
if todo.ID == id {
t.TodoList[i].Title = title
break
}
}
}
func (t *TodoServiceMemory) Clear() {
t.Lock()
defer t.Unlock()
t.TodoList = []ToDo{}
}
func (t *TodoServiceMemory) ClearCompleted() {
t.Lock()
defer t.Unlock()
var incomplete []ToDo
for _, todo := range t.TodoList {
if !todo.Done {
incomplete = append(incomplete, todo)
}
}
t.TodoList = incomplete
}
type TodoServiceDB struct {
TodoCrud
db *gorm.DB
}
func (t *TodoServiceDB) All() []ToDo {
var todos []ToDo
t.db.Order("id desc").Find(&todos)
return todos
}
func (t *TodoServiceDB) Find(id int) (ToDo, error) {
var todo ToDo
result := t.db.First(&todo, id)
if result.Error != nil {
return ToDo{}, result.Error
}
return todo, nil
}
func (t *TodoServiceDB) Add(todo ToDo) {
t.db.Create(&todo)
}
func (t *TodoServiceDB) Toggle(id int) {
var todo ToDo
t.db.First(&todo, id)
todo.Done = !todo.Done
t.db.Save(&todo)
}
func (t *TodoServiceDB) Delete(id int) {
t.db.Delete(&ToDo{}, id)
}
func (t *TodoServiceDB) Rename(id int, title string) {
var todo ToDo
t.db.First(&todo, id)
todo.Title = title
t.db.Save(&todo)
}
func (t *TodoServiceDB) Clear() {
t.db.Exec("DELETE FROM to_dos")
}
func (t *TodoServiceDB) ClearCompleted() {
t.db.Where("done = ?", true).Delete(&ToDo{})
}
func (t *TodoServiceDB) OpenTodos() []ToDo {
var todos []ToDo
t.db.Where("done = ?", false).Find(&todos)
return todos
}
func (t *TodoServiceDB) CompletedTodos() []ToDo {
var todos []ToDo
t.db.Where("done = ?", true).Find(&todos)
return todos
}
var (
//go:embed templates/*
templates embed.FS
//go:embed assets/*
assets embed.FS
)
func main() {
indexTmpl := template.Must(template.ParseFS(templates, "templates/application.go.html", "templates/index.go.html"))
renameTmpl := template.Must(template.ParseFS(templates, "templates/rename.go.html"))
db, err := gorm.Open(sqlite.Open("database.db"), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
err = db.AutoMigrate(&ToDo{})
if err != nil {
panic("failed to migrate database")
}
app := &App{
todoService: &TodoServiceDB{db: db},
m: melody.New(),
indexTmpl: indexTmpl,
renameTmpl: renameTmpl,
assets: assets,
db: db,
}
http.HandleFunc("/", app.IndexHandler)
http.HandleFunc("POST /add", app.AddHandler)
http.HandleFunc("PATCH /toggle", app.ToggleHandler)
http.HandleFunc("DELETE /delete", app.DeleteHandler)
http.HandleFunc("GET /showrename", app.ShowRenameHandler)
http.HandleFunc("PATCH /rename", app.RenameHandler)
http.HandleFunc("POST /clear", app.ClearHandler)
http.HandleFunc("POST /clearcompleted", app.ClearCompletedHandler)
http.HandleFunc("/ws", app.WebSocketHandler)
http.Handle("/assets/", app.AssetFileHandler())
log.Println("Server running at http://localhost:8080")
err = http.ListenAndServe("localhost:8080", nil)
if err != nil {
log.Fatal(err)
}
}
func (a *App) AssetFileHandler() http.Handler {
return http.FileServer(http.FS(a.assets))
}
func (a *App) IndexHandler(w http.ResponseWriter, r *http.Request) {
completedTodos := a.todoService.CompletedTodos()
completedTodosCount := len(completedTodos)
data := struct {
Timestamp int64
TodoList []ToDo
CompletedTodosCount int
}{
Timestamp: time.Now().Unix(),
TodoList: a.todoService.All(),
CompletedTodosCount: completedTodosCount,
}
// Execute the template with the data
err := a.indexTmpl.Execute(w, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (a *App) AddHandler(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
title := r.FormValue("title")
a.todoService.Add(ToDo{Title: title})
a.m.Broadcast([]byte("update"))
http.Redirect(w, r, "/", http.StatusSeeOther)
}
func (a *App) ToggleHandler(w http.ResponseWriter, r *http.Request) {
log.Println("toggle")
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
sid := r.FormValue("id")
id, err := strconv.Atoi(sid)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
a.todoService.Toggle(id)
a.m.Broadcast([]byte("update"))
http.Redirect(w, r, "/", http.StatusSeeOther)
}
func (a *App) DeleteHandler(w http.ResponseWriter, r *http.Request) {
log.Println("delete")
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
sid := r.FormValue("id")
id, err := strconv.Atoi(sid)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
a.todoService.Delete(id)
a.m.Broadcast([]byte("update"))
http.Redirect(w, r, "/", http.StatusSeeOther)
}
func (a *App) ShowRenameHandler(w http.ResponseWriter, r *http.Request) {
log.Println("show rename")
id := r.URL.Query().Get("id")
if id == "" {
http.Error(w, "id is required", http.StatusBadRequest)
return
}
iid, err := strconv.Atoi(id)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
// Get Todo by id
todo, err := a.todoService.Find(iid)
if err != nil {
http.Error(w, err.Error(), http.StatusNotFound)
return
}
// Anonymously embed the id in the template data
data := struct {
Timestamp int64
ID string
Todo ToDo
}{
Timestamp: time.Now().Unix(),
ID: id,
Todo: todo,
}
err = a.renameTmpl.Execute(w, data)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (a *App) RenameHandler(w http.ResponseWriter, r *http.Request) {
log.Println("rename")
err := r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
sid := r.FormValue("id")
id, err := strconv.Atoi(sid)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
title := r.FormValue("title")
a.todoService.Rename(id, title)
a.m.Broadcast([]byte("update"))
}
func (a *App) ClearHandler(w http.ResponseWriter, r *http.Request) {
log.Println("clear")
a.todoService.Clear()
a.m.Broadcast([]byte("update"))
http.Redirect(w, r, "/", http.StatusSeeOther)
}
func (a *App) ClearCompletedHandler(w http.ResponseWriter, r *http.Request) {
log.Println("clear completed")
a.todoService.ClearCompleted()
a.m.Broadcast([]byte("update"))
http.Redirect(w, r, "/", http.StatusSeeOther)
}
func (a *App) WebSocketHandler(w http.ResponseWriter, r *http.Request) {
if err := a.m.HandleRequest(w, r); err != nil {
log.Println("WebSocketHandler error:", err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}