Refactor out the use of rice in favor of embed (#2)

Co-authored-by: James Mills <prologic@shortcircuit.net.au>
Reviewed-on: https://git.mills.io/prologic/spyda/pulls/2
This commit is contained in:
James Mills
2022-10-05 00:19:23 +00:00
parent 7001f3bf51
commit d4ab395515
13 changed files with 270 additions and 178 deletions

View File

@@ -5,15 +5,16 @@ import (
"fmt"
"html/template"
"io"
"os"
"io/fs"
"path/filepath"
"strings"
"sync"
rice "github.com/GeertJohan/go.rice"
"github.com/Masterminds/sprig"
humanize "github.com/dustin/go-humanize"
log "github.com/sirupsen/logrus"
"git.mills.io/prologic/spyda/internal/templates"
)
const (
@@ -57,20 +58,14 @@ func (m *TemplateManager) LoadTemplates() error {
m.Lock()
defer m.Unlock()
box, err := rice.FindBox("templates")
if err != nil {
log.WithError(err).Errorf("error finding templates")
return fmt.Errorf("error finding templates: %w", err)
}
err = box.Walk("", func(path string, info os.FileInfo, err error) error {
err := fs.WalkDir(templates.FS(), ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
log.WithError(err).Error("error talking templates")
log.WithError(err).Error("error walking templates")
return fmt.Errorf("error walking templates: %w", err)
}
fname := info.Name()
if !info.IsDir() && fname != baseTemplate {
fname := d.Name()
if !d.IsDir() && fname != baseTemplate {
// Skip _partials.html and also editor swap files, to improve the development
// cycle. Editors often add suffixes to their swap files, e.g "~" or ".swp"
// (Vim) and those files are not parsable as templates, causing panics.
@@ -82,9 +77,9 @@ func (m *TemplateManager) LoadTemplates() error {
t := template.New(name).Option("missingkey=zero")
t.Funcs(m.funcMap)
template.Must(t.Parse(box.MustString(fname)))
template.Must(t.Parse(box.MustString(partialsTemplate)))
template.Must(t.Parse(box.MustString(baseTemplate)))
template.Must(t.Parse(templates.MustGetTemplate(fname)))
template.Must(t.Parse(templates.MustGetTemplate(partialsTemplate)))
template.Must(t.Parse(templates.MustGetTemplate(baseTemplate)))
m.templates[name] = t
}
@@ -136,3 +131,15 @@ func (m *TemplateManager) Exec(name string, ctx *Context) (io.WriterTo, error) {
return buf, nil
}
// RenderHTML ...
func RenderHTML(tpl string, ctx *Context) (string, error) {
t := template.Must(template.New("tpl").Parse(tpl))
buf := bytes.NewBuffer([]byte{})
err := t.Execute(buf, ctx)
if err != nil {
return "", err
}
return buf.String(), nil
}