foodoles/server.go

75 lines
1.6 KiB
Go
Raw Normal View History

2019-11-20 17:11:29 +01:00
package main
import (
2019-11-21 16:43:02 +01:00
"cadoles/foodoles/bdd"
2019-11-21 13:54:40 +01:00
"cadoles/foodoles/foodlist"
2019-11-21 16:43:02 +01:00
votefood "cadoles/foodoles/vote"
2019-11-20 17:11:29 +01:00
"html/template"
"log"
"net/http"
"time"
)
2019-11-21 13:54:40 +01:00
// Today is today
var Today = time.Now().Format("02/01/2006")
2019-11-20 17:11:29 +01:00
func main() {
http.HandleFunc("/", base)
2019-11-21 16:43:02 +01:00
http.HandleFunc("/results", resultsPage)
bdd.InitBDD()
2019-11-20 17:11:29 +01:00
log.Print("ready: listening on localhost:8080\n")
2019-11-21 13:54:40 +01:00
2019-11-20 17:11:29 +01:00
if err := http.ListenAndServe(":8080", nil); err != nil {
panic(err)
}
}
func base(w http.ResponseWriter, r *http.Request) {
2019-11-21 16:43:02 +01:00
2019-11-20 17:11:29 +01:00
if r.Method == http.MethodPost {
2019-11-21 16:43:02 +01:00
votePage(w, r)
2019-11-20 17:11:29 +01:00
} else if r.Method == http.MethodGet {
2019-11-21 16:43:02 +01:00
homePage(w, r)
2019-11-20 17:11:29 +01:00
} else {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("400 - Unsupported Request Method!"))
}
}
2019-11-21 16:43:02 +01:00
func homePage(w http.ResponseWriter, r *http.Request) {
2019-11-21 13:54:40 +01:00
foods := foodlist.GetFoodOfTheDay(Today)
paths := []string{
"./templates/index.tmpl",
2019-11-20 17:11:29 +01:00
}
2019-11-21 13:54:40 +01:00
t := template.Must(template.New("index.tmpl").ParseFiles(paths...))
err := t.Execute(w, foods)
2019-11-20 17:11:29 +01:00
if err != nil {
log.Printf("\nExecute error: %v", err)
return
}
}
2019-11-21 16:43:02 +01:00
func resultsPage(w http.ResponseWriter, r *http.Request) {
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
}
}
2019-11-21 13:54:40 +01:00
2019-11-21 16:43:02 +01:00
func votePage(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
option := r.Form.Get("option")
log.Print("vote for : ", option)
votefood.ForFood(Today, option)
2019-11-21 13:54:40 +01:00
2019-11-21 16:43:02 +01:00
w.WriteHeader(http.StatusOK)
w.Header().Set("Content-Type", "application/json")
w.Write([]byte("Success vote for: " + option))
2019-11-20 17:11:29 +01:00
}