-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler.go
100 lines (88 loc) · 2.52 KB
/
handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package web
import (
"context"
"html/template"
"net/http"
"github.com/alexedwards/scs/v2"
"github.com/go-chi/chi/v5"
"github.com/go-chi/chi/v5/middleware"
"github.com/google/uuid"
"github.com/gorilla/csrf"
"github.com/noloman/goreddit"
)
type Handler struct {
*chi.Mux
store goreddit.Store
sessions *scs.SessionManager
}
func NewHandler(store goreddit.Store, sessions *scs.SessionManager, csrfKey []byte) *Handler {
h := &Handler{
Mux: chi.NewMux(),
store: store,
sessions: sessions,
}
threads := ThreadsHandler{store: store, sessions: sessions}
comments := CommentsHandler{store: store, sessions: sessions}
posts := PostsHandler{store: store, sessions: sessions}
users := UserHandler{store: store, sessions: sessions}
h.Use(middleware.Logger)
h.Use(csrf.Protect(csrfKey, csrf.Secure(false)))
h.Use(sessions.LoadAndSave)
h.Use(h.withUser)
h.Get("/", h.Home())
h.Route("/threads", func(r chi.Router) {
// THREADS
r.Get("/", threads.List())
r.Get("/new", threads.Create())
r.Post("/", threads.Store())
r.Post("/{id}/delete", threads.Delete())
r.Get("/{id}", threads.Show())
// POSTS
r.Post("/{id}", posts.Store())
r.Get("/{threadID}/new", posts.Create())
r.Get("/{threadID}/{postID}", posts.Show())
// COMMENTS
r.Post("/{threadID}/{postID}", comments.Store())
})
h.Get("/comments/{id}/vote", comments.Vote())
h.Get("/posts/{id}/vote", posts.Vote()) // TODO Should this be here or inside /threads?
// REGISTRATION
h.Get("/register", users.Register())
h.Post("/register", users.RegisterSubmit())
// LOGIN
h.Get("/login", users.Login())
h.Post("/login", users.LoginSubmit())
// LOGOUT
h.Get("/logout", users.Logout())
return h
}
func (h *Handler) Home() http.HandlerFunc {
type data struct {
SessionData
Posts []goreddit.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,
SessionData: GetSessionData(h.sessions, r.Context()),
})
}
}
func (h *Handler) withUser(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id, _ := h.sessions.Get(r.Context(), "user_id").(uuid.UUID)
user, err := h.store.User(id)
if err != nil {
next.ServeHTTP(w, r)
return
}
ctx := context.WithValue(r.Context(), "user", user)
next.ServeHTTP(w, r.WithContext(ctx))
})
}