diff options
Diffstat (limited to 'controllers/topic.go')
-rw-r--r-- | controllers/topic.go | 103 |
1 files changed, 103 insertions, 0 deletions
diff --git a/controllers/topic.go b/controllers/topic.go new file mode 100644 index 0000000..50f65e7 --- /dev/null +++ b/controllers/topic.go @@ -0,0 +1,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)) +} |