tulip/cmd/red-tulip/pages/pages.go

59 lines
1.1 KiB
Go
Raw Normal View History

2024-01-29 23:45:46 +00:00
package pages
2023-09-06 22:20:09 +01:00
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
wwwPages embed.FS
wwwTemplates *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() {
var o fs.FS = wwwPages
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)
o = overlapfs.OverlapFS{A: wwwPages, B: wdFs}
}
2024-01-29 23:45:46 +00:00
wwwTemplates, err = template.New("pages").Funcs(template.FuncMap{
2023-10-09 20:31:41 +01:00
"emailHide": EmailHide,
}).ParseFS(o, "*.go.html")
})
return err
2023-09-06 22:20:09 +01:00
}
func RenderPageTemplate(wr io.Writer, name string, data any) {
2023-10-09 20:31:41 +01:00
err := wwwTemplates.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
}
func EmailHide(a string) string {
b := []byte(a)
for i := range b {
if b[i] != '@' && b[i] != '.' {
b[i] = 'x'
}
}
return string(b)
}