go-todos-app/handlers/todoHandler.go
Michael Thomson 6f7bcc9503
All checks were successful
ci/woodpecker/push/build Pipeline was successful
ci/woodpecker/push/dryrun Pipeline was successful
ci/woodpecker/push/publish-tag Pipeline was successful
ci/woodpecker/push/publish-latest Pipeline was successful
postgres and such
2024-06-17 23:37:43 -04:00

126 lines
2.5 KiB
Go

package handlers
import (
"net/http"
"github.com/gofrs/uuid/v5"
"michaelthomson.dev/mthomson/go-todos-app/services"
"michaelthomson.dev/mthomson/go-todos-app/templates/partials"
)
type TodoHandler struct {
ts *services.TodoService
}
func NewTodoHandler(ts *services.TodoService) TodoHandler {
return TodoHandler{ts: ts}
}
func (h *TodoHandler) Create(w http.ResponseWriter, r *http.Request) {
var err error
err = r.ParseForm()
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
name := r.FormValue("name")
addedTodo, err := h.ts.AddTodo(name)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
err = partials.Todo(addedTodo).Render(r.Context(), w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (h *TodoHandler) Done(w http.ResponseWriter, r *http.Request) {
var err error
id, err := uuid.FromString(r.PathValue("id"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
todo, err := h.ts.GetTodoById(id)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
todo, err = h.ts.UpdateTodo(id, todo.Name, true)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
err = partials.Todo(todo).Render(r.Context(), w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (h *TodoHandler) Undone(w http.ResponseWriter, r *http.Request) {
var err error
id, err := uuid.FromString(r.PathValue("id"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
todo, err := h.ts.GetTodoById(id)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
todo, err = h.ts.UpdateTodo(id, todo.Name, false)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
err = partials.Todo(todo).Render(r.Context(), w)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (h *TodoHandler) Delete(w http.ResponseWriter, r *http.Request) {
var err error
id, err := uuid.FromString(r.PathValue("id"))
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
err = h.ts.DeleteTodoById(id)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}