lavender/pages/pages.go

59 lines
1.1 KiB
Go
Raw Normal View History

2023-10-08 15:24:59 +01:00
package pages
import (
"embed"
_ "embed"
"errors"
"github.com/1f349/overlapfs"
2023-10-08 15:24:59 +01:00
"html/template"
2023-10-09 00:04:28 +01:00
"io"
"io/fs"
"log"
2023-10-08 15:24:59 +01:00
"os"
"path/filepath"
2023-10-09 00:04:28 +01:00
"sync"
2023-10-08 15:24:59 +01:00
)
var (
//go:embed *.go.html
2024-02-07 01:18:17 +00:00
wwwPages embed.FS
wwwTemplates *template.Template
loadOnce sync.Once
2023-10-08 15:24:59 +01:00
)
2023-10-09 00:04:28 +01:00
func LoadPages(wd string) (err error) {
loadOnce.Do(func() {
2024-02-07 01:18:17 +00:00
var o fs.FS = wwwPages
2023-10-09 00:04:28 +01:00
if wd != "" {
wwwDir := filepath.Join(wd, "www")
err = os.Mkdir(wwwDir, os.ModePerm)
if err != nil && !errors.Is(err, os.ErrExist) {
2023-10-09 00:04:28 +01:00
return
}
wdFs := os.DirFS(wwwDir)
2024-02-07 01:18:17 +00:00
o = overlapfs.OverlapFS{A: wwwPages, B: wdFs}
2023-10-09 00:04:28 +01:00
}
2024-02-07 01:18:17 +00:00
wwwTemplates, err = template.New("pages").Funcs(template.FuncMap{
"emailHide": EmailHide,
}).ParseFS(o, "*.go.html")
2023-10-09 00:04:28 +01:00
})
return err
}
func RenderPageTemplate(wr io.Writer, name string, data any) {
2024-02-07 01:18:17 +00:00
err := wwwTemplates.ExecuteTemplate(wr, name+".go.html", data)
if err != nil {
2023-10-09 00:04:28 +01:00
log.Printf("Failed to render page: %s: %s\n", name, err)
}
2023-10-08 15:24:59 +01:00
}
2024-02-07 01:18:17 +00:00
func EmailHide(a string) string {
b := []byte(a)
for i := range b {
if b[i] != '@' && b[i] != '.' {
b[i] = 'x'
}
}
return string(b)
}