48 lines
949 B
Go
48 lines
949 B
Go
|
|
package httpapi
|
||
|
|
|
||
|
|
import (
|
||
|
|
"embed"
|
||
|
|
"html/template"
|
||
|
|
"net/http"
|
||
|
|
"path"
|
||
|
|
"strings"
|
||
|
|
"sync"
|
||
|
|
)
|
||
|
|
|
||
|
|
//go:embed templates/*.tmpl
|
||
|
|
var uiFS embed.FS
|
||
|
|
|
||
|
|
//go:embed static/*
|
||
|
|
var staticFS embed.FS
|
||
|
|
|
||
|
|
var (
|
||
|
|
tplOnce sync.Once
|
||
|
|
tpl *template.Template
|
||
|
|
)
|
||
|
|
|
||
|
|
func (s *Server) parseTemplatesOnce() {
|
||
|
|
tplOnce.Do(func() {
|
||
|
|
// Parse all templates under templates/
|
||
|
|
t := template.New("base").Funcs(template.FuncMap{})
|
||
|
|
t = template.Must(t.ParseFS(uiFS, "templates/*.tmpl"))
|
||
|
|
tpl = t
|
||
|
|
})
|
||
|
|
}
|
||
|
|
|
||
|
|
func (s *Server) render(w http.ResponseWriter, name string, data map[string]any) {
|
||
|
|
s.parseTemplatesOnce()
|
||
|
|
if data == nil {
|
||
|
|
data = map[string]any{}
|
||
|
|
}
|
||
|
|
data["Version"] = s.Version
|
||
|
|
data["Commit"] = s.Commit
|
||
|
|
base := strings.TrimSuffix(path.Base(name), path.Ext(name))
|
||
|
|
if base == "dashboard" {
|
||
|
|
data["Title"] = "sojuboy"
|
||
|
|
} else {
|
||
|
|
data["Title"] = strings.Title(base)
|
||
|
|
}
|
||
|
|
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||
|
|
_ = tpl.ExecuteTemplate(w, name, data)
|
||
|
|
}
|