update: service, handlers, and db separation
This commit is contained in:
61
handlers/todoHandler.go
Normal file
61
handlers/todoHandler.go
Normal file
@@ -0,0 +1,61 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"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.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
err = partials.Todo(addedTodo).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.Parse(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
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user