Skip to content

Instantly share code, notes, and snippets.

@bastianccm
Created February 26, 2020 13:22
Show Gist options
  • Save bastianccm/d572354fc0472594a7812fb8c0bcd996 to your computer and use it in GitHub Desktop.
Save bastianccm/d572354fc0472594a7812fb8c0bcd996 to your computer and use it in GitHub Desktop.
package polls
import (
"context"
"strconv"
"flamingo.me/flamingo/v3/framework/web"
"github.com/jinzhu/gorm"
)
type controller struct {
responder *web.Responder
db *gorm.DB
}
func (c *controller) Inject(responder *web.Responder, db *gorm.DB) {
c.responder = responder
c.db = db
}
func (c *controller) index(ctx context.Context, request *web.Request) web.Result {
var viewData struct {
LatestQuestionList []Question
}
c.db.Limit(5).Order("id desc").Find(&viewData.LatestQuestionList)
return c.responder.Render("index", viewData)
}
type viewData struct {
Question Question
ErrorMessage string
}
func (c *controller) viewDataOrError(questionIDstr string) (*viewData, web.Result) {
questionID, err := strconv.Atoi(questionIDstr)
if err != nil {
return nil, c.responder.ServerError(err)
}
var viewData viewData
if c.db.Preload("Choices").First(&viewData.Question, questionID).RecordNotFound() {
return nil, c.responder.NotFound(gorm.ErrRecordNotFound)
}
return &viewData, nil
}
func (c *controller) detail(ctx context.Context, request *web.Request) web.Result {
viewData, result := c.viewDataOrError(request.Params["question_id"])
if result != nil {
return result
}
return c.responder.Render("detail", viewData)
}
func (c *controller) results(ctx context.Context, request *web.Request) web.Result {
viewData, result := c.viewDataOrError(request.Params["question_id"])
if result != nil {
return result
}
return c.responder.Render("results", viewData)
}
func (c *controller) vote(ctx context.Context, request *web.Request) web.Result {
viewData, result := c.viewDataOrError(request.Params["question_id"])
if result != nil {
return result
}
var choice Choice
choiceIDstr, err := request.Form1("choice")
if err != nil {
return c.noSelectedChoice(viewData.Question)
}
choiceID, err := strconv.Atoi(choiceIDstr)
if err != nil {
return c.noSelectedChoice(viewData.Question)
}
for _, c := range viewData.Question.Choices {
if c.ID == uint(choiceID) {
choice = c
break
}
}
if choice.ID == 0 {
return c.noSelectedChoice(viewData.Question)
}
choice.Votes++
c.db.Save(&choice)
return c.responder.RouteRedirect("results", map[string]string{"question_id": strconv.Itoa(int(viewData.Question.ID))})
}
func (c *controller) noSelectedChoice(question Question) web.Result {
var viewData struct {
Question Question
ErrorMessage string
}
viewData.Question = question
viewData.ErrorMessage = "You didn't select a choice."
return c.responder.Render("detail", viewData)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment