package webserver import ( "fmt" "html/template" "net/http" "strconv" "snamellit.com/play/todo/internal/persist" ) func PathHandleFunc(path string, f func(http.ResponseWriter, *http.Request)) { http.Handle(path, http.StripPrefix(path, http.HandlerFunc(f))) } func IndexHandler(w http.ResponseWriter, r *http.Request) { t, _ := template.ParseFiles("templates/index.html") t.Execute(w, nil) } func renderTodos(w http.ResponseWriter) { fmt.Println("renderTodos") todos,err := persist.GetTodos() if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, "Error: %s", err) } t, _ := template.ParseFiles("templates/todos.html") t.Execute(w, todos) } func TodosHandler(w http.ResponseWriter, r *http.Request) { fmt.Println("TodosHandler") if r.Method == "POST" { r.ParseForm() todoTitle := r.Form.Get("title") persist.AddTodo(todoTitle) } renderTodos(w) } func ToggleTodoHandler(w http.ResponseWriter, r *http.Request) { fmt.Println("ToggleTodoHandler") todoId, err := strconv.Atoi(r.URL.Path) if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, "Error: %s", err) } fmt.Println("Toggle Todo Id: %d", todoId) todo, err := persist.GetTodoById(todoId) if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, "Error: %s", err) } todo.Completed = !todo.Completed err = persist.SetTodo(todo) if err != nil { w.WriteHeader(http.StatusInternalServerError) fmt.Fprintf(w, "Error: %s", err) } renderTodos(w) } func TodoHandler(w http.ResponseWriter, r *http.Request) { if r.Method != "DELETE" { w.WriteHeader(http.StatusMethodNotAllowed) fmt.Fprintf(w, "Method %s not allowed", r.Method) return } todoId, err := strconv.Atoi(r.URL.Path) if err != nil { panic(err) } fmt.Println("Todo Id: %d", todoId) persist.DeleteTodoById(todoId) TodosHandler(w, r) return }