tulip/purple-server/pages/pages.go

47 lines
885 B
Go
Raw Normal View History

2023-09-06 22:20:09 +01:00
package pages
import (
"embed"
_ "embed"
2023-10-09 20:31:41 +01:00
"errors"
"github.com/1f349/overlapfs"
2023-09-06 22:20:09 +01:00
"html/template"
"io"
2023-10-09 20:31:41 +01:00
"io/fs"
"log"
2023-10-09 20:31:41 +01:00
"os"
"path/filepath"
"sync"
2023-09-06 22:20:09 +01:00
)
var (
2023-10-09 20:31:41 +01:00
//go:embed *.go.html
2024-01-29 10:44:45 +00:00
flowPages embed.FS
flowTemplates *template.Template
loadOnce sync.Once
2023-09-06 22:20:09 +01:00
)
2023-10-09 20:31:41 +01:00
func LoadPages(wd string) (err error) {
loadOnce.Do(func() {
2024-01-29 10:44:45 +00:00
var o fs.FS = flowPages
2023-10-09 20:31:41 +01:00
if wd != "" {
wwwDir := filepath.Join(wd, "www")
err = os.Mkdir(wwwDir, os.ModePerm)
if err != nil && !errors.Is(err, os.ErrExist) {
return
}
wdFs := os.DirFS(wwwDir)
2024-01-29 10:44:45 +00:00
o = overlapfs.OverlapFS{A: flowPages, B: wdFs}
2023-10-09 20:31:41 +01:00
}
2024-01-29 10:44:45 +00:00
flowTemplates, err = template.ParseFS(o, "*.go.html")
2023-10-09 20:31:41 +01:00
})
return err
2023-09-06 22:20:09 +01:00
}
func RenderPageTemplate(wr io.Writer, name string, data any) {
2024-01-29 10:44:45 +00:00
err := flowTemplates.ExecuteTemplate(wr, name+".go.html", data)
if err != nil {
log.Printf("Failed to render page: %s: %s\n", name, err)
}
2023-09-06 22:20:09 +01:00
}