package main import ( "errors" "fmt" "html/template" "io" "os" "github.com/Gleipnir-Technology/nidus-sync/models" ) var ( dashboard = newBuiltTemplate("dashboard", "base") signin = newBuiltTemplate("signin", "base") signup = newBuiltTemplate("signup", "base") ) type BuiltTemplate struct { files []string template *template.Template } type Link struct { Href string Title string } type ContentDashboard struct { BabbleLinks []Link Username string } type ContentSignin struct { InvalidCredentials bool } type ContentSignup struct { } func (bt *BuiltTemplate) ExecuteTemplate(w io.Writer, data any) error { name := bt.files[0] + ".html" if bt.template == nil { templ, err := parseFromDisk(bt.files) if err != nil { return fmt.Errorf("Failed to parse template file: %v", err) } if templ == nil { w.Write([]byte("Failed to read from disk: ")) return errors.New("Template parsing failed") } return templ.ExecuteTemplate(w, name, data) } else { return bt.template.ExecuteTemplate(w, name, data) } } func htmlDashboard(w io.Writer, user *models.User) error { data := ContentDashboard{ Username: user.Username, } return dashboard.ExecuteTemplate(w, data) } func htmlSignin(w io.Writer, errorCode string) error { data := ContentSignin{ InvalidCredentials: errorCode == "invalid-credentials", } return signin.ExecuteTemplate(w, data) } func htmlSignup(w io.Writer, path string) error { data := ContentSignup{ } return signup.ExecuteTemplate(w, data) } func makeFuncMap() template.FuncMap { funcMap := template.FuncMap{} return funcMap } func newBuiltTemplate(files ...string) BuiltTemplate { files_on_disk := true for _, f := range files { full_path := "templates/" + f + ".html" _, err := os.Stat(full_path) if err != nil { files_on_disk = false break } } if files_on_disk { return BuiltTemplate{ files: files, template: nil, } } return BuiltTemplate{ files: files, template: parseEmbedded(files), } } func parseEmbedded(files []string) *template.Template { return nil } func parseFromDisk(files []string) (*template.Template, error) { funcMap := makeFuncMap() paths := make([]string, 0) for _, f := range files { paths = append(paths, "templates/"+f+".html") } name := files[0] + ".html" templ, err := template.New(name).Funcs(funcMap).ParseFiles(paths...) if err != nil { return nil, fmt.Errorf("Failed to parse %s: %v", paths, err) } return templ, nil }