From f238fc7a63c162361b4cc7eef8d1f98ce6e785ef Mon Sep 17 00:00:00 2001 From: Jona Heitzer Date: Wed, 1 Jan 2025 22:20:14 +0100 Subject: [PATCH] Add result page --- server.go | 52 +++++++++++++++++++- static/result.html.tmpl | 105 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 155 insertions(+), 2 deletions(-) create mode 100644 static/result.html.tmpl diff --git a/server.go b/server.go index 2295408..ceb511c 100644 --- a/server.go +++ b/server.go @@ -17,8 +17,9 @@ const ( ) var ( - db *sql.DB - indexHtmlTemplate *template.Template + db *sql.DB + indexHtmlTemplate *template.Template + resultHtmlTemplate *template.Template ) type ChoicesPost struct { @@ -64,10 +65,16 @@ func initDatabase() { func prepareStaticContent() { var err error + indexHtmlTemplate, err = template.ParseFiles("./static/index.html.tmpl") if err != nil { log.Fatalf("[!] Could not parse index.html template, error: %s\n", err) } + + resultHtmlTemplate, err = template.ParseFiles("./static/result.html.tmpl") + if err != nil { + log.Fatalf("[!] Could not parse result.html template, error: %s\n", err) + } } func handleGetRoot(w http.ResponseWriter, r *http.Request) { @@ -106,6 +113,42 @@ func handleGetRoot(w http.ResponseWriter, r *http.Request) { } func handleGetResult(w http.ResponseWriter, r *http.Request) { + var pollName string + pollId, err := strconv.Atoi(r.PathValue("pollId")) + if err != nil { + log.Printf("[!] Invallid poll id url segment, error: %s\n", err) + http.Error(w, "Poll not found", http.StatusBadRequest) + return + } + + const query = ` + SELECT name + FROM polls + WHERE id = ?; + ` + + err = db.QueryRow(query, pollId).Scan(&pollName) + if err != nil { + log.Printf("[!] No poll with id %d was found, error: %s\n", pollId, err) + http.Error(w, "Poll not found", http.StatusBadRequest) + return + } + + err = resultHtmlTemplate.Execute(w, struct { + PollId int + PollName string + }{ + PollId: pollId, + PollName: pollName, + }) + if err != nil { + log.Printf("[!] Could not execute result.html template, error: %s\n", err) + http.Error(w, "Error rendering template", http.StatusInternalServerError) + } + +} + +func handleGetResultApi(w http.ResponseWriter, r *http.Request) { pollId, err := strconv.Atoi(r.PathValue("pollId")) if err != nil { log.Printf("[!] Invallid poll id url segment, error: %s\n", err) @@ -290,6 +333,11 @@ func main() { handleOptionsSubmit, ) + http.HandleFunc( + "GET /api/result/{pollId}", + handleGetResultApi, + ) + log.Printf("[*] Datefinder server listening on :%s\n", PORT) if err := http.ListenAndServe(":8080", nil); err != nil { log.Fatalf("[!] Could not start server on %s, error: %s\n", PORT, err) diff --git a/static/result.html.tmpl b/static/result.html.tmpl new file mode 100644 index 0000000..babd237 --- /dev/null +++ b/static/result.html.tmpl @@ -0,0 +1,105 @@ + + + + + + + Datefinder + + + + +

Datefinder

+

{{ .PollName }}

+
+ + + +