aboutsummaryrefslogblamecommitdiff
path: root/controllers/post.go
blob: aee7c978908c2e3f904f6c5bb084d0affca1cc4a (plain) (tree)









































                                                                                               
package controllers

import (
	"errors"
	"fmt"
	"net/http"

	"gitrepo.ru/neonxp/gorum/contextlib"
	"gitrepo.ru/neonxp/gorum/views"
	"go.neonxp.ru/mux"
)

func (rt *Router) NewPost(w http.ResponseWriter, r *http.Request) {
	req := new(postRequest)
	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
	}

	topic, err := rt.topicRepo.Get(uint64(req.Parent))
	if err != nil {
		mux.Render(w, r, mux.DefaultErrorHandler(err))
		return
	}

	if r.Method == http.MethodPost {
		postID, err := rt.postRepo.CreatePost(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#post%d", req.Parent, postID))
		return
	}

	mux.Render(w, r, views.NewPost(topic))
}