package web import ( "html/template" "net/http" "git.snrd.de/Spaenny/goddit" "github.com/go-chi/chi" "github.com/google/uuid" ) type ThreadHandler struct { store goddit.Store } func (h *ThreadHandler) List() http.HandlerFunc { type data struct { Threads []goddit.Thread } tmpl := template.Must(template.ParseFiles("templates/layout.html", "templates/threads.html")) return func(w http.ResponseWriter, r *http.Request) { tt, err := h.store.Threads() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } tmpl.Execute(w, data{Threads: tt}) } } func (h *ThreadHandler) Create() http.HandlerFunc { tmpl := template.Must(template.ParseFiles("templates/layout.html", "templates/thread_create.html")) return func(w http.ResponseWriter, r *http.Request) { tmpl.Execute(w, nil) } } func (h *ThreadHandler) Show() http.HandlerFunc { type data struct { Thread goddit.Thread Posts []goddit.Post } tmpl := template.Must(template.ParseFiles("templates/layout.html", "templates/thread.html")) return func(w http.ResponseWriter, r *http.Request) { idStr := chi.URLParam(r, "id") id, err := uuid.Parse(idStr) if err != nil { http.NotFound(w, r) return } t, err := h.store.Thread(id) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } pp, err := h.store.PostsByThread(t.ID) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } tmpl.Execute(w, data{Thread: t, Posts: pp}) } } func (h *ThreadHandler) Store() http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { title := r.FormValue("title") description := r.FormValue("description") if err := h.store.CreateThread(&goddit.Thread{ ID: uuid.New(), Title: title, Description: description, }); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } http.Redirect(w, r, "/threads", http.StatusFound) } } func (h *ThreadHandler) Delete() http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { idStr := chi.URLParam(r, "id") id, err := uuid.Parse(idStr) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } if err := h.store.DeleteThread(id); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } http.Redirect(w, r, "/threads", http.StatusFound) } }