lavender/pages/pages.go

80 lines
1.5 KiB
Go
Raw Permalink Normal View History

2023-10-08 15:24:59 +01:00
package pages
import (
"bytes"
2023-10-08 15:24:59 +01:00
"embed"
_ "embed"
"errors"
2024-05-13 20:33:25 +01:00
"github.com/1f349/lavender/logger"
"github.com/1f349/lavender/utils"
"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"
2023-10-08 15:24:59 +01:00
"os"
"path/filepath"
2023-10-08 15:24:59 +01:00
)
var (
//go:embed *.go.html assets/*.css
2024-02-07 01:18:17 +00:00
wwwPages embed.FS
wwwTemplates *template.Template
loadOnce utils.Once[error]
cssAssetMap = make(map[string][]byte)
2023-10-08 15:24:59 +01:00
)
func LoadPages(wd string) error {
return loadOnce.Do(func() (err error) {
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) {
return err
2023-10-09 00:04:28 +01:00
}
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")
glob, err := fs.Glob(o, "assets/*")
if err != nil {
return err
}
for _, i := range glob {
cssAssetMap[i], err = fs.ReadFile(o, i)
if err != nil {
return err
}
}
return nil
2023-10-09 00:04:28 +01:00
})
}
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 {
2024-05-13 20:33:25 +01:00
logger.Logger.Warn("Failed to render page", "name", name, "err", err)
}
2023-10-08 15:24:59 +01:00
}
2024-02-07 01:18:17 +00:00
func RenderCss(name string) io.ReadSeeker {
b, ok := cssAssetMap[name]
if !ok {
return nil
}
return bytes.NewReader(b)
}
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)
}