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
101
102
103
|
package controllers
import (
"errors"
"fmt"
"net/http"
"strconv"
"gitrepo.ru/neonxp/gorum/contextlib"
"gitrepo.ru/neonxp/gorum/models"
"gitrepo.ru/neonxp/gorum/views"
"go.neonxp.ru/mux"
)
func (rt *Router) Index(w http.ResponseWriter, r *http.Request) {
topics, err := rt.topicRepo.List(0)
if err != nil {
mux.Render(w, r, mux.DefaultErrorHandler(err))
return
}
mux.Render(w, r, views.Topics(topics))
}
func (rt *Router) Topic(w http.ResponseWriter, r *http.Request) {
sParentID := r.PathValue("id")
parentID, err := strconv.Atoi(sParentID)
if err != nil {
mux.Render(w, r, mux.DefaultErrorHandler(err))
return
}
topic, err := rt.topicRepo.Get(uint64(parentID))
if err != nil {
mux.Render(w, r, mux.DefaultErrorHandler(err))
return
}
topics, err := rt.topicRepo.List(uint64(parentID))
if err != nil {
mux.Render(w, r, mux.DefaultErrorHandler(err))
return
}
posts, err := rt.postRepo.List(uint64(parentID))
if err != nil {
mux.Render(w, r, mux.DefaultErrorHandler(err))
return
}
emailToUser := map[string]*models.User{}
for _, p := range posts {
u, ok := emailToUser[p.AuthorID]
if !ok {
u, err = rt.userRepo.Get(p.AuthorID)
if err != nil {
u = &models.User{Username: "user-not-found"}
}
}
emailToUser[p.AuthorID] = u
p.Author = u
}
mux.Render(w, r, views.Posts(topic, topics, posts))
}
func (rt *Router) NewTopic(w http.ResponseWriter, r *http.Request) {
req := new(topicRequest)
if err := mux.Bind(r, req); err != nil {
mux.Render(w, r, mux.DefaultErrorHandler(err))
return
}
user := contextlib.GetUser(r.Context())
if user == nil {
mux.Render(w, r, mux.DefaultErrorHandler(errors.New("403")))
return
}
if r.Method == http.MethodPost {
topic, err := rt.topicRepo.Create(req.Topic, req.Text, user.Email, uint64(req.Parent))
if err != nil {
mux.Render(w, r, mux.DefaultErrorHandler(err))
return
}
mux.Redirect(w, 302, fmt.Sprintf("/t/%d", topic.ID))
return
}
topic := &models.Topic{
ID: 0,
Topic: "Корень",
}
sTopicID := r.PathValue("topic")
if sTopicID != "" {
if topicID, err := strconv.Atoi(sTopicID); err == nil {
topic, err = rt.topicRepo.Get(uint64(topicID))
if err != nil {
mux.Render(w, r, mux.DefaultErrorHandler(err))
return
}
}
}
mux.Render(w, r, views.NewTopic(topic))
}
|