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/comment_handler.go

74 lines
1.5 KiB
Go
Raw Normal View History

package web
import (
"net/http"
"git.snrd.de/Spaenny/goddit"
2021-08-29 17:09:48 +02:00
"github.com/alexedwards/scs/v2"
"github.com/go-chi/chi"
"github.com/google/uuid"
)
type CommentHandler struct {
2021-08-29 17:09:48 +02:00
store goddit.Store
sessions *scs.SessionManager
}
func (h *CommentHandler) Store() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
content := r.FormValue("content")
idStr := chi.URLParam(r, "postID")
id, err := uuid.Parse(idStr)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := h.store.CreateComment(&goddit.Comment{
ID: uuid.New(),
PostID: id,
Content: content,
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
2021-08-29 17:43:45 +02:00
h.sessions.Put(r.Context(), "flash", "Your Comment has been added.")
http.Redirect(w, r, r.Referer(), http.StatusFound)
}
}
func (h *CommentHandler) Vote() 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
}
c, err := h.store.Comment(id)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
dir := r.URL.Query().Get("dir")
if dir == "up" {
c.Votes++
} else if dir == "down" {
c.Votes--
}
if err := h.store.UpdateComment(&c); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
http.Redirect(w, r, r.Referer(), http.StatusFound)
}
}