foodoles/server.go

103 lines
1.9 KiB
Go
Raw Normal View History

2019-11-20 17:11:29 +01:00
package main
import (
"bufio"
"encoding/csv"
"html/template"
"io"
"io/ioutil"
"log"
"net/http"
"os"
"time"
"github.com/Joker/jade"
)
type FoodOfTheDay struct {
Date string
Foods map[string]string
}
func main() {
http.HandleFunc("/", base)
http.HandleFunc("/results", results)
log.Print("ready: listening on localhost:8080\n")
food()
if err := http.ListenAndServe(":8080", nil); err != nil {
panic(err)
}
}
func base(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
log.Printf("vote")
} else if r.Method == http.MethodGet {
home(w, r)
} else {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte("400 - Unsupported Request Method!"))
}
}
func home(w http.ResponseWriter, r *http.Request) {
dat, err := ioutil.ReadFile("./templates/index.go")
if err != nil {
log.Printf("ReadFile error: %v", err)
return
}
tmpl, err := jade.Parse("index", []byte(dat))
if err != nil {
log.Printf("Parse error: %v", err)
return
}
w.Write([]byte(tmpl))
}
func results(w http.ResponseWriter, r *http.Request) {
dat, err := ioutil.ReadFile("./templates/results.go")
if err != nil {
log.Printf("ReadFile error: %v", err)
return
}
tmpl, err := jade.Parse("results", []byte(dat))
if err != nil {
log.Printf("Parse error: %v", err)
return
}
goTpl, err := template.New("html").Parse(tmpl)
if err != nil {
log.Printf("\nTemplate parse error: %v", err)
return
}
err = goTpl.Execute(w, "")
if err != nil {
log.Printf("\nExecute error: %v", err)
return
}
}
func food() {
foodcsv, _ := os.Open("csv/foods.csv")
foodreader := csv.NewReader(bufio.NewReader(foodcsv))
foods := FoodOfTheDay{time.Now().Format("20060102"), make(map[string]string)}
for {
line, err := foodreader.Read()
if err == io.EOF {
break
} else if err != nil {
log.Fatal(err)
}
foods.Foods[line[0]] = line[1]
}
log.Printf("%+q", foods)
}