From ebea1c07fdc451997c0240edf1f62e2969f80d0e Mon Sep 17 00:00:00 2001 From: Jona Heitzer Date: Wed, 1 Jan 2025 15:26:49 +0100 Subject: [PATCH] 400 favico request and parameterize pollId --- server.go | 29 +++++++++++++++++++++++++---- static/index.html.tmpl | 2 +- 2 files changed, 26 insertions(+), 5 deletions(-) diff --git a/server.go b/server.go index 408a60c..06f687b 100644 --- a/server.go +++ b/server.go @@ -7,6 +7,7 @@ import ( "html/template" "log" "net/http" + "strconv" _ "github.com/mattn/go-sqlite3" ) @@ -71,22 +72,34 @@ func prepareStaticContent() { } func handleGetRoot(w http.ResponseWriter, r *http.Request) { - var pollId = r.PathValue("pollId") 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) + err = db.QueryRow(query, pollId).Scan(&pollName) if err != nil { - log.Printf("[!] No poll with id %s was found, error: %s\n", pollId, err) + log.Printf("[!] No poll with id %d was found, error: %s\n", pollId, err) http.Error(w, "Poll not found", http.StatusBadRequest) return } - err = indexHtmlTemplate.Execute(w, struct{ PollName string }{PollName: pollName}) + err = indexHtmlTemplate.Execute(w, struct { + PollId int + PollName string + }{ + PollId: pollId, + PollName: pollName, + }) if err != nil { log.Printf("[!] Could not execute index.html template, error: %s\n", err) http.Error(w, "Error rendering template", http.StatusInternalServerError) @@ -112,6 +125,7 @@ func handlePostSubmit(w http.ResponseWriter, r *http.Request) { if err != nil { log.Printf("[!] Error decoding request Body %v, error: %s\n", r.Body, err) w.WriteHeader(http.StatusBadRequest) + return } choicesJson, err := json.Marshal(choicesPost.Choices) @@ -164,6 +178,13 @@ func main() { handleGetPing, ) + http.HandleFunc( + "GET /favicon.ico", + func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "There is no favicon.ico!", http.StatusBadRequest) + }, + ) + http.HandleFunc( "GET /{pollId}", handleGetRoot, diff --git a/static/index.html.tmpl b/static/index.html.tmpl index bc73e53..37b18b2 100644 --- a/static/index.html.tmpl +++ b/static/index.html.tmpl @@ -115,7 +115,7 @@ headers: { "Content-Type": "application/json", // Inform the server about the data format }, - body: JSON.stringify({pollId: 1, username: submitName.value, choices: choices}), // Convert the data to JSON string + body: JSON.stringify({pollId: {{ .PollId }}, username: submitName.value, choices: choices}), // Convert the data to JSON string }) /* .then(response => {