about summary refs log tree commit diff stats
path: root/frontend/assets.go
blob: 7a90d80e32f8199df2aa0fd76f4408e3cf7e68ca (plain)
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package frontend

import (
	"crypto/sha256"
	"encoding/base64"
	"fmt"
	"hash/fnv"
	"io"
	"io/fs"

	"github.com/pkg/errors"
)

var Assets = &AssetCollection{
	Scripts:     []*Asset{},
	Stylesheets: []*Asset{},
	ByPath:      make(map[string]*Asset),
}

type Asset struct {
	URL          string
	ETag         string
	Filename     string
	Base64SHA256 string
}

type AssetCollection struct {
	Scripts     []*Asset
	Stylesheets []*Asset
	ByPath      map[string]*Asset
}

func newAsset(filename string) (*Asset, error) {
	file, err := Files.Open(filename)
	if err != nil {
		return nil, errors.WithMessagef(err, "could not open file %s", filename)
	}
	defer file.Close()

	shasum := sha256.New()
	hash := fnv.New64a()
	if _, err := io.Copy(io.MultiWriter(shasum, hash), file); err != nil {
		return nil, errors.WithMessagef(err, "could not hash file %s", filename)
	}

	return &Asset{
		URL:          "/" + filename,
		ETag:         fmt.Sprintf(`W/"%x"`, hash.Sum(nil)),
		Filename:     filename,
		Base64SHA256: base64.StdEncoding.EncodeToString(shasum.Sum(nil)),
	}, nil
}

func hashScripts() error {
	scripts, err := fs.Glob(Files, "static/**.js")
	if err != nil {
		return errors.WithMessage(err, "could not glob files")
	}
	for _, filename := range scripts {
		asset, err := newAsset(filename)
		if err != nil {
			return err
		}
		Assets.Scripts = append(Assets.Scripts, asset)
		Assets.ByPath[asset.URL] = asset
	}

	return nil
}

func hashStyles() error {
	styles, err := fs.Glob(Files, "static/**.css")
	if err != nil {
		return errors.WithMessage(err, "could not glob files")
	}
	for _, filename := range styles {
		asset, err := newAsset(filename)
		if err != nil {
			return err
		}
		Assets.Stylesheets = append(Assets.Stylesheets, asset)
		Assets.ByPath[asset.URL] = asset
	}

	return nil
}

func Rehash() (err error) {
	err = hashScripts()
	if err != nil {
		return err
	}
	err = hashStyles()
	if err != nil {
		return err
	}

	return nil
}

func init() {
	err := Rehash()
	if err != nil {
		panic(err)
	}
}