Files
shop-go/internal/handlers/home.go
T

72 lines
1.7 KiB
Go

package handlers
import (
"embed"
"html/template"
"io/fs"
"log"
"net/http"
"regexp"
"shop/internal/models"
"shop/internal/orderstatus"
)
//go:embed templates/*
var templateFS embed.FS
//go:embed static/*
var staticFS embed.FS
var tagRe = regexp.MustCompile(`<[^>]*>`)
func stripHTML(s string) string {
return tagRe.ReplaceAllString(s, "")
}
func effectivePrice(p models.Product) float64 { return p.EffectivePrice() }
func ParseTemplates() (*template.Template, error) {
funcMap := template.FuncMap{
"plain": stripHTML,
"effective": effectivePrice,
"safeHTML": func(s string) template.HTML { return template.HTML(s) },
"orderLabel": orderstatus.Label,
"orderIcon": orderstatus.Icon,
"orderClass": orderstatus.Class,
"orderStep": orderstatus.Step,
"orderTimeline": func() []string { return orderstatus.Timeline },
"stepDone": func(status, step string) bool {
cur, s := orderstatus.Step(status), orderstatus.Step(step)
return cur > 0 && s > 0 && s < cur
},
"stepCurrent": func(status, step string) bool {
return orderstatus.Step(status) == orderstatus.Step(step)
},
"orderTerminal": orderstatus.IsTerminal,
"orderNorm": orderstatus.Normalize,
"historyBarPct": func(price, max float64) int {
if max <= 0 {
return 20
}
pct := int(price / max * 100)
if pct < 8 {
return 8
}
return pct
},
"catSelected": func(catID int, productCatID *int) bool {
return productCatID != nil && *productCatID == catID
},
}
return template.New("").Funcs(funcMap).ParseFS(templateFS, "templates/*.html")
}
func StaticHandler() http.Handler {
sub, err := fs.Sub(staticFS, "static")
if err != nil {
log.Fatal(err)
}
return http.FileServer(http.FS(sub))
}