2021-08-29 16:37:20 +02:00
|
|
|
package web
|
|
|
|
|
|
|
|
import (
|
|
|
|
"html/template"
|
|
|
|
"net/http"
|
|
|
|
|
|
|
|
"git.snrd.de/Spaenny/goddit"
|
|
|
|
"github.com/go-chi/chi"
|
|
|
|
"github.com/go-chi/chi/middleware"
|
2021-08-29 16:55:23 +02:00
|
|
|
"github.com/gorilla/csrf"
|
2021-08-29 16:37:20 +02:00
|
|
|
)
|
|
|
|
|
2021-08-29 16:55:23 +02:00
|
|
|
func NewHandler(store goddit.Store, csrfKey []byte) *Handler {
|
2021-08-29 16:37:20 +02:00
|
|
|
h := &Handler{
|
|
|
|
Mux: chi.NewMux(),
|
|
|
|
store: store,
|
|
|
|
}
|
|
|
|
|
|
|
|
threads := ThreadHandler{store: store}
|
|
|
|
posts := PostHandler{store: store}
|
|
|
|
comments := CommentHandler{store: store}
|
|
|
|
|
|
|
|
h.Use(middleware.Logger)
|
2021-08-29 16:55:23 +02:00
|
|
|
h.Use(csrf.Protect(csrfKey, csrf.Secure(false)))
|
2021-08-29 16:37:20 +02:00
|
|
|
|
|
|
|
h.Get("/", h.Home())
|
|
|
|
h.Route("/threads", func(r chi.Router) {
|
|
|
|
r.Get("/", threads.List())
|
|
|
|
r.Get("/new", threads.Create())
|
|
|
|
r.Post("/", threads.Store())
|
|
|
|
r.Get("/{id}", threads.Show())
|
|
|
|
r.Post("/{id}/delete", threads.Delete())
|
|
|
|
r.Get("/{id}/new", posts.Create())
|
|
|
|
r.Post("/{id}", posts.Store())
|
|
|
|
r.Get("/{threadID}/{postID}", posts.Show())
|
|
|
|
r.Get("/{threadID}/{postID}/vote", posts.Vote())
|
|
|
|
r.Post("/{threadID}/{postID}", comments.Store())
|
|
|
|
})
|
|
|
|
h.Get("/comments/{id}/vote", comments.Vote())
|
|
|
|
|
|
|
|
return h
|
|
|
|
}
|
|
|
|
|
|
|
|
type Handler struct {
|
|
|
|
*chi.Mux
|
|
|
|
|
|
|
|
store goddit.Store
|
|
|
|
}
|
|
|
|
|
|
|
|
func (h *Handler) Home() http.HandlerFunc {
|
|
|
|
type data struct {
|
|
|
|
Posts []goddit.Post
|
|
|
|
}
|
|
|
|
|
|
|
|
tmpl := template.Must(template.ParseFiles("templates/layout.html", "templates/home.html"))
|
|
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
|
|
pp, err := h.store.Posts()
|
|
|
|
if err != nil {
|
|
|
|
http.Error(w, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
tmpl.Execute(w, data{Posts: pp})
|
|
|
|
}
|
|
|
|
}
|