From 3dce44a652f93d2f9974a918cf7c22e78fabaaa7 Mon Sep 17 00:00:00 2001 From: Jason Staten Date: Sun, 14 Aug 2022 23:46:16 -0600 Subject: [PATCH] counts --- main.go | 59 ++++++++++++++++++++++++++++++++++++++++++++---- views/_task.html | 9 ++++---- views/list.html | 6 +++-- 3 files changed, 64 insertions(+), 10 deletions(-) diff --git a/main.go b/main.go index d61b407..9f6ad34 100644 --- a/main.go +++ b/main.go @@ -41,8 +41,9 @@ type Todo struct { } type ViewModel struct { - Todos []Todo - Only string + Todos []Todo + Only string + Incomplete int } func filterSlice[T any](xs []T, pred func(T) bool) []T { @@ -57,6 +58,17 @@ func filterSlice[T any](xs []T, pred func(T) bool) []T { return result } +func countSlice[T any](xs []T, pred func(T) bool) int { + count := 0 + for _, element := range xs { + if pred(element) { + count += 1 + } + } + + return count +} + func main() { todos := make([]Todo, 0, 10) @@ -75,9 +87,12 @@ func main() { renderTodos = filterSlice(todos, func(todo Todo) bool { return todo.Completed }) } + incomplete := countSlice(todos, func(todo Todo) bool { return !todo.Completed }) + vm := ViewModel{ - Todos: renderTodos, - Only: only, + Todos: renderTodos, + Only: only, + Incomplete: incomplete, } err := t.Render(w, "list.html", vm) if err != nil { @@ -127,6 +142,42 @@ func main() { w.Header().Set("Location", "/") w.WriteHeader(http.StatusSeeOther) }) + + http.HandleFunc("/destroy", func(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + + if err := r.ParseForm(); err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + + id := r.Form.Get("id") + todos = filterSlice(todos, func(t Todo) bool { return t.Id != id }) + + w.Header().Set("Location", "/") + w.WriteHeader(http.StatusSeeOther) + }) + + http.HandleFunc("/clear", func(w http.ResponseWriter, r *http.Request) { + if r.Method != "POST" { + w.WriteHeader(http.StatusMethodNotAllowed) + return + } + + if err := r.ParseForm(); err != nil { + w.WriteHeader(http.StatusBadRequest) + return + } + + todos = filterSlice(todos, func(t Todo) bool { return !t.Completed }) + + w.Header().Set("Location", "/") + w.WriteHeader(http.StatusSeeOther) + }) + log.Print("Running on 8080") log.Fatal(http.ListenAndServe(":8080", nil)) } diff --git a/views/_task.html b/views/_task.html index d12d0a0..274e997 100644 --- a/views/_task.html +++ b/views/_task.html @@ -1,12 +1,13 @@
  • - +
    - + +
    + +
  • diff --git a/views/list.html b/views/list.html index f83b0c3..5065653 100644 --- a/views/list.html +++ b/views/list.html @@ -20,7 +20,7 @@ {{end}}