busdepartures/server.go

65 lines
1.2 KiB
Go

package main
import (
"embed"
"fmt"
"html/template"
"log"
"net/http"
"strconv"
"time"
)
//go:embed static
var staticDir embed.FS
//go:embed index.html
var indexTemplate string
type TemplateQuay struct {
Name string
Town string
Departures []Departure
}
type TemplateContext struct {
Quays []TemplateQuay
}
func formatTime(t time.Time) string {
return t.Format("15:04")
}
var tplFunctions = template.FuncMap{"formatTime": formatTime}
func serveHttp(port int) {
http.HandleFunc("/", handleIndex)
http.Handle("/static/", http.FileServer(http.FS(staticDir)))
log.Printf("Listening on port %s\n", strconv.Itoa(port))
err := http.ListenAndServe(fmt.Sprintf(":%s", strconv.Itoa(port)), nil)
if err != nil {
log.Fatal(err)
}
}
func handleIndex(w http.ResponseWriter, r *http.Request) {
var ctxt = TemplateContext{}
for _, quay := range Quays {
departures, err := getDepartures(quay)
if err != nil {
log.Printf("Error retrieving departures for quay '%s'", quay.ID)
continue
}
ctxt.Quays = append(ctxt.Quays, TemplateQuay{quay.Name, quay.Town, departures})
}
tpl := template.New("index.html").Funcs(tplFunctions)
tpl, _ = tpl.Parse(indexTemplate)
_ = tpl.Execute(w, ctxt)
}