xonecas.io
8356
Wx

www-xonecas-io / files

www-xonecas-io / internal / site / assets.go

1.5 KB
1package site
2
3import (
4	"crypto/sha256"
5	"fmt"
6	"io/fs"
7	"os"
8	"os/exec"
9	"strings"
10)
11
12// versions maps each asset's path to a hash of its content. Pages link an asset with ?v=<hash>,
13// so a new build of an asset gets a new address, and browsers fetch it again.
14var versions = map[string]string{}
15
16// asset is the address of the asset at p, with its version.
17func asset(p string) string {
18	if v, ok := versions[strings.TrimPrefix(p, "/")]; ok {
19		return p + "?v=" + v
20	}
21	return p
22}
23
24// Version is the content hash pages link the asset at path p with, "" for none.
25func Version(p string) string { return versions[p] }
26
27// Assets is every file the pages link, by path: the embedded static files, and site.css compiled by a tailwind
28// binary. It versions them all, so call it once, before the first page renders.
29func Assets(tailwind string) (map[string][]byte, error) {
30	files := map[string][]byte{}
31	err := fs.WalkDir(static, "static", func(path string, d fs.DirEntry, err error) error {
32		if err != nil || d.IsDir() {
33			return err
34		}
35		files[strings.TrimPrefix(path, "static/")], err = static.ReadFile(path)
36		return err
37	})
38	if err != nil {
39		return nil, err
40	}
41	if tailwind != "" {
42		cmd := exec.Command(tailwind, "-i", "internal/site/assets/site.css", "--minify")
43		cmd.Stderr = os.Stderr
44		if files["site.css"], err = cmd.Output(); err != nil {
45			return nil, fmt.Errorf("tailwind: %w", err)
46		}
47	}
48	versions = map[string]string{}
49	for name, b := range files {
50		versions[name] = fmt.Sprintf("%x", sha256.Sum256(b))[:10]
51	}
52	return files, nil
53}