-
-
Notifications
You must be signed in to change notification settings - Fork 69
/
tplFuncs.go
61 lines (47 loc) · 1017 Bytes
/
tplFuncs.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
package main
import (
"crypto/sha512"
"encoding/base64"
"sync"
"text/template"
"github.com/Masterminds/sprig/v3"
)
var (
sriCacheStore = newSRICache()
tplFuncs template.FuncMap
)
func init() {
tplFuncs = sprig.FuncMap()
tplFuncs["assetSRI"] = assetSRIHash
}
func assetSRIHash(assetName string) string {
if sri, ok := sriCacheStore.Get(assetName); ok {
return sri
}
data, err := assets.ReadFile(assetName)
if err != nil {
panic(err)
}
h := sha512.New384()
_, _ = h.Write(data)
sum := h.Sum(nil)
sri := "sha384-" + base64.StdEncoding.EncodeToString(sum)
sriCacheStore.Set(assetName, sri)
return sri
}
type sriCache struct {
c map[string]string
l sync.RWMutex
}
func newSRICache() *sriCache { return &sriCache{c: map[string]string{}} }
func (s *sriCache) Get(assetName string) (string, bool) {
s.l.RLock()
defer s.l.RUnlock()
h, ok := s.c[assetName]
return h, ok
}
func (s *sriCache) Set(assetName, hash string) {
s.l.Lock()
defer s.l.Unlock()
s.c[assetName] = hash
}