2023-10-08 15:24:59 +01:00
|
|
|
package pages
|
|
|
|
|
|
|
|
import (
|
|
|
|
"embed"
|
|
|
|
_ "embed"
|
2023-10-09 16:42:50 +01:00
|
|
|
"errors"
|
2023-10-08 16:43:27 +01:00
|
|
|
"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"
|
2023-10-08 16:43:27 +01:00
|
|
|
"path/filepath"
|
2023-10-09 00:04:28 +01:00
|
|
|
"sync"
|
2023-10-08 15:24:59 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
2023-10-08 16:43:27 +01:00
|
|
|
//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)
|
2023-10-09 16:42:50 +01:00
|
|
|
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)
|
2023-10-08 16:43:27 +01:00
|
|
|
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 16:43:27 +01:00
|
|
|
}
|
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)
|
|
|
|
}
|