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/handler.go
2021-08-29 16:55:23 +02:00

65 lines
1.4 KiB
Go

package web
import (
"html/template"
"net/http"
"git.snrd.de/Spaenny/goddit"
"github.com/go-chi/chi"
"github.com/go-chi/chi/middleware"
"github.com/gorilla/csrf"
)
func NewHandler(store goddit.Store, csrfKey []byte) *Handler {
h := &Handler{
Mux: chi.NewMux(),
store: store,
}
threads := ThreadHandler{store: store}
posts := PostHandler{store: store}
comments := CommentHandler{store: store}
h.Use(middleware.Logger)
h.Use(csrf.Protect(csrfKey, csrf.Secure(false)))
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})
}
}