-
Notifications
You must be signed in to change notification settings - Fork 6
/
helpers.go
70 lines (57 loc) · 1.27 KB
/
helpers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package web
import (
"embed"
"html/template"
"io"
"io/fs"
"net/http"
"strings"
"github.com/Masterminds/sprig/v3"
)
func CreateTemplateEngine(embedFS embed.FS, subpath string) *template.Template {
root := template.New("").Funcs(sprig.HtmlFuncMap())
sub, _ := fs.Sub(embedFS, subpath)
err := fs.WalkDir(sub, ".", func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if !d.IsDir() {
f, errOpen := sub.Open(path)
if errOpen != nil {
return errOpen
}
b, errRead := io.ReadAll(f)
if errRead != nil {
return errRead
}
t := root.New(path)
_, errParse := t.Parse(string(b))
if errParse != nil {
return errParse
}
}
return nil
})
return template.Must(root, err)
}
type binaryFileSystem struct {
fs http.FileSystem
}
func (b *binaryFileSystem) Open(name string) (http.File, error) {
return b.fs.Open(name)
}
func (b *binaryFileSystem) Exists(prefix string, filepath string) bool {
if p := strings.TrimPrefix(filepath, prefix); len(p) < len(filepath) {
if _, err := b.fs.Open(p); err != nil {
return false
}
return true
}
return false
}
func EmbeddedFS(embedFS embed.FS, subdir string) *binaryFileSystem {
sub, _ := fs.Sub(embedFS, subdir)
return &binaryFileSystem{
fs: http.FS(sub),
}
}