Parameterize route and index.html template to allow serving specific poll
This commit is contained in:
@@ -64,14 +64,29 @@ func initDatabase() {
|
||||
|
||||
func prepareStaticContent() {
|
||||
var err error
|
||||
indexHtmlTemplate, err = template.ParseFiles("./static/index.html")
|
||||
indexHtmlTemplate, err = template.ParseFiles("./static/index.html.tmpl")
|
||||
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)
|
||||
var pollId = r.PathValue("pollId")
|
||||
var pollName string
|
||||
const query = `
|
||||
SELECT name
|
||||
FROM polls
|
||||
WHERE id = ?;
|
||||
`
|
||||
|
||||
err := db.QueryRow(query, pollId).Scan(&pollName)
|
||||
if err != nil {
|
||||
log.Printf("[!] No poll with id %s 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})
|
||||
if err != nil {
|
||||
log.Printf("[!] Could not execute index.html template, error: %s\n", err)
|
||||
http.Error(w, "Error rendering template", http.StatusInternalServerError)
|
||||
@@ -123,7 +138,6 @@ func handlePostSubmit(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
tx.Commit()
|
||||
|
||||
log.Printf("[*] Persisted choices for poll %d, username %s to database\n",
|
||||
@@ -151,7 +165,7 @@ func main() {
|
||||
)
|
||||
|
||||
http.HandleFunc(
|
||||
"GET /",
|
||||
"GET /{pollId}",
|
||||
handleGetRoot,
|
||||
)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user