all repos — go-lift @ main

Lightweight workout tracker prototype..

src/ui/ui.go (view raw)

 1package ui
 2
 3import (
 4	"bytes"
 5	"html/template"
 6	"net/http"
 7	"os"
 8)
 9
10const (
11	base      = "base"
12	templates = "templates"
13	ps        = string(os.PathSeparator)
14
15	basePath      = "templates" + ps + base + ".gohtml"
16	homePath      = "templates" + ps + "home.gohtml"
17	exercisesPath = "templates" + ps + "exercises.gohtml"
18	routinesPath  = "templates" + ps + "routines.gohtml"
19	workoutsPath  = "templates" + ps + "workouts.gohtml"
20	profilePath   = "templates" + ps + "profile.gohtml"
21)
22
23var (
24	tmpl    map[string]*template.Template
25	funcMap = template.FuncMap{
26		"capitalize": capitalize,
27	}
28)
29
30type PageData struct {
31	Page string
32}
33
34func parseTemplate(path string) *template.Template {
35	return template.Must(template.New(base).Funcs(funcMap).ParseFiles(path, basePath))
36}
37
38func executeTemplateSafe(w http.ResponseWriter, t string, data any) {
39	var buf bytes.Buffer
40	if err := tmpl[t].ExecuteTemplate(&buf, base, data); err != nil {
41		http.Error(w, err.Error(), http.StatusInternalServerError)
42		return
43	}
44	buf.WriteTo(w)
45}
46
47func getHome(w http.ResponseWriter, r *http.Request) {
48	executeTemplateSafe(w, homePath, &PageData{Page: "home"})
49}
50
51func getExercises(w http.ResponseWriter, r *http.Request) {
52	executeTemplateSafe(w, exercisesPath, &PageData{Page: "exercises"})
53}
54
55func getRoutines(w http.ResponseWriter, r *http.Request) {
56	executeTemplateSafe(w, routinesPath, &PageData{Page: "routines"})
57}
58
59func getWorkouts(w http.ResponseWriter, r *http.Request) {
60	executeTemplateSafe(w, workoutsPath, &PageData{Page: "workouts"})
61}
62
63func getProfile(w http.ResponseWriter, r *http.Request) {
64	executeTemplateSafe(w, profilePath, &PageData{Page: "profile"})
65}
66
67func InitServeMux(s *http.ServeMux) {
68	tmpl = make(map[string]*template.Template)
69
70	tmpl[homePath] = parseTemplate(homePath)
71	tmpl[exercisesPath] = parseTemplate(exercisesPath)
72	tmpl[routinesPath] = parseTemplate(routinesPath)
73	tmpl[workoutsPath] = parseTemplate(workoutsPath)
74	tmpl[profilePath] = parseTemplate(profilePath)
75
76	s.HandleFunc("GET /", getHome)
77	s.HandleFunc("GET /exercises", getExercises)
78	s.HandleFunc("GET /routines", getRoutines)
79	s.HandleFunc("GET /workouts", getWorkouts)
80	s.HandleFunc("GET /profile", getProfile)
81
82	s.HandleFunc("GET /static/", func(w http.ResponseWriter, r *http.Request) {
83		http.StripPrefix("/static/", http.FileServer(http.Dir("static"))).ServeHTTP(w, r)
84	})
85}