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
|
package handlers
import (
"fmt"
"demoon/config"
"demoon/internal/database/repos"
"demoon/internal/models"
"html/template"
"log/slog"
"net/http"
"os"
)
// Handlers structure
type Handlers struct {
cfg config.Config
log *slog.Logger
repo repos.FullRepo
}
// NewHandlers constructor
func NewHandlers(
cfg config.Config, l *slog.Logger, repo repos.FullRepo,
) *Handlers {
if l == nil {
l = slog.New(slog.NewJSONHandler(os.Stdout, nil))
}
h := &Handlers{
cfg: cfg,
log: l,
repo: repo,
}
return h
}
func (h *Handlers) Ping(w http.ResponseWriter, r *http.Request) {
h.log.Info("got ping request")
w.Write([]byte("pong"))
}
func (h *Handlers) HandleAnswer(w http.ResponseWriter, r *http.Request) {
if err := r.ParseForm(); err != nil {
abortWithError(w, "Invalid form data")
return
}
selectedIndex := r.FormValue("selected")
questionID := r.FormValue("question_id")
h.log.Info("answer received",
"selected", selectedIndex,
"question_id", questionID)
// Get question from database
question, err := h.repo.DBGetQuestion(questionID)
if err != nil {
h.log.Error("failed to get question", "error", err, "question_id", questionID)
abortWithError(w, "Question not found")
return
}
var feedback string
if selectedIndex == fmt.Sprint(question.CorrectIndex) {
feedback = `<div class="feedback">Correct! 🎉</div>`
} else {
feedback = `<div class="feedback">Wrong answer, try again! ❌</div>`
}
w.Header().Set("Content-Type", "text/html")
w.Write([]byte(feedback))
}
func (h *Handlers) MainPage(w http.ResponseWriter, r *http.Request) {
tmpl, err := template.ParseGlob("components/*.html")
if err != nil {
abortWithError(w, err.Error())
return
}
testQuestion := &models.Question{
ID: 1,
Text: "___ du keine Zweifel daran?",
Option1: "Haben",
Option2: "Hast",
Option3: "Hat",
Option4: "Habt",
CorrectIndex: 1,
Requirement: "Choose the correct verb form",
Explanation: "Use 'Hast' for 2nd person singular",
Status: 0,
ExamID: 1,
MixedID: 101,
}
err = tmpl.ExecuteTemplate(w, "main", testQuestion)
if err != nil {
h.log.Error("failed to render template", "error", err)
abortWithError(w, "Failed to render page")
}
}
|