This repository has been archived on 2021-09-01. You can view files and clone it, but cannot push or open issues or pull requests.
goddit/web/thread_handler.go

117 lines
2.6 KiB
Go

package web
import (
"html/template"
"net/http"
"git.snrd.de/Spaenny/goddit"
"github.com/alexedwards/scs/v2"
"github.com/go-chi/chi"
"github.com/google/uuid"
"github.com/gorilla/csrf"
)
type ThreadHandler struct {
store goddit.Store
sessions *scs.SessionManager
}
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 {
type data struct {
CSRF template.HTML
}
tmpl := template.Must(template.ParseFiles("templates/layout.html", "templates/thread_create.html"))
return func(w http.ResponseWriter, r *http.Request) {
tmpl.Execute(w, data{
CSRF: csrf.TemplateField(r),
})
}
}
func (h *ThreadHandler) Show() http.HandlerFunc {
type data struct {
CSRF template.HTML
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{
CSRF: csrf.TemplateField(r),
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)
}
}