From e4e745cb57e55f92f7dd02cce63cdbcee7277039 Mon Sep 17 00:00:00 2001 From: Jona Heitzer Date: Wed, 1 Jan 2025 14:33:35 +0100 Subject: [PATCH] Serve html from golang server via template --- .gitignore | 1 + server.go | 44 ++++++++++++++++++++++++-- static/index.html | 79 ++++++++++++++++++++++++++++++++++++++++++++++- 3 files changed, 120 insertions(+), 4 deletions(-) diff --git a/.gitignore b/.gitignore index 9edb214..cd024c8 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,4 @@ *.sqlite3 *.sqlite3-journal .DS_Store +.vscode diff --git a/server.go b/server.go index 85736a9..31b652a 100644 --- a/server.go +++ b/server.go @@ -4,6 +4,7 @@ import ( "database/sql" "encoding/json" "fmt" + "html/template" "log" "net/http" @@ -16,7 +17,8 @@ const ( ) var ( - db *sql.DB + db *sql.DB + indexHtmlTemplate *template.Template ) type ChoicesPost struct { @@ -60,6 +62,22 @@ func initDatabase() { } } +func prepareStaticContent() { + var err error + indexHtmlTemplate, err = template.ParseFiles("./static/index.html") + if err != nil { + log.Fatalf("[!] Could not parse index.html template, error: %s\n", err) + } +} + +func handleGetRoot(w http.ResponseWriter, r *http.Request) { + err := indexHtmlTemplate.Execute(w, nil) + if err != nil { + log.Printf("[!] Could not execute index.html template, error: %s\n", err) + http.Error(w, "Error rendering template", http.StatusInternalServerError) + } +} + func handleGetPing(w http.ResponseWriter, r *http.Request) { log.Printf("[*] Received request %v %v\n", r.Method, r.URL) fmt.Fprintf(w, "PONG\n") @@ -86,17 +104,30 @@ func handlePostSubmit(w http.ResponseWriter, r *http.Request) { log.Printf("[!] Could not marshal choices, error: %s\n", err) } + tx, err := db.Begin() + if err != nil { + log.Printf("[!] Could not begin database transaction, error: %s\n", err) + w.WriteHeader(http.StatusBadRequest) + return + } + const query = ` INSERT INTO choices (pollid, username, choices) VALUES (?, ?, ?); ` - _, err = db.Exec(query, choicesPost.PollId, choicesPost.Username, string(choicesJson)) + _, err = tx.Exec(query, choicesPost.PollId, choicesPost.Username, string(choicesJson)) if err != nil { log.Printf("[!] Could not insert choices into database, error: %s\n", err) + tx.Rollback() + w.WriteHeader(http.StatusBadRequest) + return } - log.Printf("[*] Persisted choices for %s to database\n", "DUMMY USERNAME") + tx.Commit() + + log.Printf("[*] Persisted choices for poll %d, username %s to database\n", + choicesPost.PollId, choicesPost.Username) w.WriteHeader(http.StatusOK) } @@ -112,11 +143,18 @@ func main() { initDatabase() defer db.Close() + prepareStaticContent() + http.HandleFunc( "GET /api/ping", handleGetPing, ) + http.HandleFunc( + "GET /", + handleGetRoot, + ) + http.HandleFunc( "POST /api/submit", handlePostSubmit, diff --git a/static/index.html b/static/index.html index 3e32ca3..97b299e 100644 --- a/static/index.html +++ b/static/index.html @@ -54,7 +54,84 @@ - +