package serve import ( "errors" "net/http" "git.andreafazzi.eu/andrea/probo/pkg/models" "github.com/charmbracelet/log" ) var ExamHandler = func(c *Controller, w http.ResponseWriter, r *http.Request) { _, err := ValidateJwtCookie(r) if err != nil { panic(err) } participantID := r.PathValue("participantID") session, err := c.sStore.Read(r.PathValue("uuid")) if err != nil { panic(err) } exam, ok := session.Exams[participantID] if !ok { panic(errors.New("Exam not found in the store!")) } examWithSession := struct { *models.Exam Session *models.Session }{exam, session} switch r.Method { case http.MethodGet: log.Info("Sending exam to", "participant", exam.Participant, "exam", exam) err = c.ExecuteTemplate(w, examWithSession) if err != nil { panic(err) } case http.MethodPost: err := r.ParseForm() if err != nil { panic(err) } answers := make([]*models.ParticipantAnswer, 0) participant := session.Participants[participantID] for quizID, values := range r.Form { correct := false quiz := session.Quizzes[quizID] for _, answerID := range values { if quiz.Correct.ID == answerID { correct = true } answers = append(answers, &models.ParticipantAnswer{Quiz: quiz, Answer: session.Answers[answerID], Correct: correct}) } } response, err := c.rStore.Create( &models.Response{ SessionTitle: session.Title, Participant: participant, Answers: answers, }) if err != nil { panic(err) } log.Info("Saving response", "response", response) } }