Add result page
This commit is contained in:
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user