foodoles/server.go

91 lines
2.0 KiB
Go

package main
import (
"cadoles/foodoles/bdd"
"cadoles/foodoles/foodlist"
"cadoles/foodoles/vote"
"html/template"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", Base)
http.HandleFunc("/results", ResultsPage)
db, err := bdd.OpenDB()
if err != nil {
log.Printf("\nOpenDB error: %v", err)
return
}
bdd.CloseDB(db)
vote.GetVotesOfTheDay()
log.Print("\nready: listening on localhost:8080\n")
if err := http.ListenAndServe(":8080", nil); err != nil {
panic(err)
}
}
// Base is the entry point to all requests
func Base(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
VotePage(w, r)
} else if r.Method == http.MethodGet {
HomePage(w, r)
} else {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("400 - Unsupported Request Method!"))
}
}
// HomePage is the homepage of the app
func HomePage(w http.ResponseWriter, r *http.Request) {
foods := foodlist.GetFoodOfTheDay()
paths := []string{
"./templates/index.tmpl",
}
t := template.Must(template.New("index.tmpl").ParseFiles(paths...))
err := t.Execute(w, foods)
if err != nil {
log.Printf("\nExecute error: %v", err)
return
}
}
// ResultsPage is the page displaiyng the votes results
func ResultsPage(w http.ResponseWriter, r *http.Request) {
db, err := bdd.OpenDB()
if err != nil {
log.Printf("\nOpenDB error: %v", err)
return
}
//vote, _ := bdd.GetVotesOfTheDay(db, time.Now().AddDate(0, 0, -1))
bdd.CloseDB(db)
paths := []string{
"./templates/results.tmpl",
}
t := template.Must(template.New("results.tmpl").ParseFiles(paths...))
err = t.Execute(w, "")
if err != nil {
log.Printf("\nExecute error: %v", err)
return
}
}
// VotePage is the endpoint to add votes
func VotePage(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
option := r.Form.Get("option")
log.Print("vote for : ", option)
vote.ForFood(option)
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("Success vote for: " + option))
}