package main import ( "cadoles/foodoles/bdd" "cadoles/foodoles/foodlist" votefood "cadoles/foodoles/vote" "html/template" "log" "net/http" "time" ) // Today is today var Today = time.Now().Format("02/01/2006") func main() { http.HandleFunc("/", base) http.HandleFunc("/results", resultsPage) bdd.InitBDD() log.Print("ready: listening on localhost:8080\n") if err := http.ListenAndServe(":8080", nil); err != nil { panic(err) } } 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!")) } } func homePage(w http.ResponseWriter, r *http.Request) { foods := foodlist.GetFoodOfTheDay(Today) 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 } } 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 } } func votePage(w http.ResponseWriter, r *http.Request) { r.ParseForm() option := r.Form.Get("option") log.Print("vote for : ", option) votefood.ForFood(Today, option) w.WriteHeader(http.StatusOK) w.Header().Set("Content-Type", "application/json") w.Write([]byte("Success vote for: " + option)) }