-
Notifications
You must be signed in to change notification settings - Fork 4
/
embed.go
46 lines (38 loc) · 840 Bytes
/
embed.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
package assets
import (
"embed"
"fmt"
"mime"
"path/filepath"
"github.com/pkg/errors"
"projectforge.dev/projectforge/app/util"
)
//go:embed *
var FS embed.FS
type Entry struct {
Bytes []byte
Mime string
Hash string
}
var cache = map[string]*Entry{}
func Embed(path string) (*Entry, error) {
if path == "embed.go" {
return nil, errors.New("invalid asset")
}
if x, ok := cache[path]; ok {
return x, nil
}
data, err := FS.ReadFile(path)
if err != nil {
return nil, errors.Wrapf(err, "error reading asset at [%s]", path)
}
mt := mime.TypeByExtension(filepath.Ext(path))
h := util.HashFNV128UUID(string(data))
e := &Entry{Bytes: data, Mime: mt, Hash: h.String()[:8]}
cache[path] = e
return e, nil
}
func URL(path string) string {
e, _ := Embed(path)
return fmt.Sprintf("/assets/%s?hash=%s", path, e.Hash)
}